Zebra logs timing for facet results
[idzebra-moved-to-github.git] / index / retrieve.c
1 /* $Id: retrieve.c,v 1.83 2008-01-16 11:54:28 adam Exp $
2    Copyright (C) 1995-2007
3    Index Data ApS
4
5 This file is part of the Zebra server.
6
7 Zebra is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 2, or (at your option) any later
10 version.
11
12 Zebra is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
20
21 */
22
23 #include <stdio.h>
24 #include <assert.h>
25
26 #include <fcntl.h>
27 #ifdef WIN32
28 #include <io.h>
29 #include <process.h>
30 #endif
31 #if HAVE_UNISTD_H
32 #include <unistd.h>
33 #endif
34
35 #include "index.h"
36 #include <yaz/diagbib1.h>
37 #include <yaz/snprintf.h>
38 #include <direntz.h>
39 #include <yaz/oid_db.h>
40 #include <zebra_strmap.h>
41
42 #define MAX_SYSNOS_PER_RECORD 40
43
44 #define ZEBRA_XML_HEADER_STR "<record xmlns=\"http://www.indexdata.com/zebra/\""
45
46 static int zebra_create_record_stream(ZebraHandle zh, 
47                                       Record *rec,
48                                       struct ZebraRecStream *stream)
49 {
50     RecordAttr *recordAttr = rec_init_attr(zh->reg->zei, *rec);
51
52     if ((*rec)->size[recInfo_storeData] > 0)
53         zebra_create_stream_mem(stream, (*rec)->info[recInfo_storeData],
54                                 (*rec)->size[recInfo_storeData]);
55     else
56     {
57         char full_rep[1024];
58         int fd;
59             
60         if (zh->path_reg && !yaz_is_abspath((*rec)->info[recInfo_filename])){
61             strcpy(full_rep, zh->path_reg);
62             strcat(full_rep, "/");
63             strcat(full_rep, (*rec)->info[recInfo_filename]);
64         }
65         else
66             strcpy(full_rep, (*rec)->info[recInfo_filename]);
67             
68         if ((fd = open(full_rep, O_BINARY|O_RDONLY)) == -1){
69             yaz_log(YLOG_WARN|YLOG_ERRNO, "Retrieve fail; missing file: %s",
70                      full_rep);
71             rec_free(rec);
72             return YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
73         }
74         zebra_create_stream_fd(stream, fd, recordAttr->recordOffset);
75     }
76     return 0;
77 }
78     
79
80 struct index_spec {
81     const char *index_name;
82     const char *index_type;
83     const char *extra;
84     struct index_spec *next;
85 };
86
87
88 struct index_spec *parse_index_spec(const char *elem, NMEM nmem,
89                                     int *error)
90 {
91     struct index_spec *first = 0;
92     struct index_spec **last = &first;
93     const char *cp = elem;
94
95     *error = 0;
96     if (cp[0] == ':' && cp[1] == ':')
97     {
98
99         cp++; /* skip first ':' */
100
101         for (;;)
102         {
103             const char *cp0;
104             struct index_spec *spec = nmem_malloc(nmem, sizeof(*spec));
105             spec->index_type = 0;
106             spec->next = 0;
107             spec->extra = 0;
108
109             if (!first)
110                 first = spec;
111             *last = spec;
112             last = &spec->next;
113
114             cp++; /* skip ',' or second ':' */
115             cp0 = cp;
116             while (*cp != ':' && *cp != '\0' && *cp != ',')
117                 cp++;
118             spec->index_name = nmem_strdupn(nmem, cp0, cp - cp0);
119             if (*cp == ':') /* type as well */
120             {
121                 cp++;
122                 cp0 = cp;
123                 
124                 while (*cp != '\0' && *cp != ',' && *cp != ':')
125                     cp++;
126                 spec->index_type = nmem_strdupn(nmem, cp0, cp - cp0);
127             }
128             if (*cp == ':') /* extra arguments */
129             {
130                 cp++;
131                 cp0 = cp;
132                 
133                 while (*cp != '\0' && *cp != ',' && *cp != ':')
134                     cp++;
135                 spec->extra = nmem_strdupn(nmem, cp0, cp - cp0);
136             }
137             if (*cp != ',')
138                 break;
139         }
140     }
141     if (*cp != '\0')
142         *error = 1;
143     return first;
144 }
145                             
146 static int parse_zebra_elem(const char *elem,
147                             const char **index, size_t *index_len,
148                             const char **type, size_t *type_len)
149 {
150     *index = 0;
151     *index_len = 0;
152
153     *type = 0;
154     *type_len = 0;
155
156     if (elem && *elem)
157     {
158         char *cp;
159         /* verify that '::' is in the beginning of *elem 
160            and something more follows */
161         if (':' != *elem
162             || !(elem +1) || ':' != *(elem +1)
163             || !(elem +2) || '\0' == *(elem +2))
164             return 0;
165  
166         /* pick out info from string after '::' */
167         elem = elem + 2;
168         cp = strchr(elem, ':');
169
170         if (!cp) /* index, no colon, no type */
171         {
172             *index = elem;
173             *index_len = strlen(elem);
174         }
175         else if (cp[1] == '\0') /* colon, but no following type */
176         {
177             return 0;
178         }
179         else  /* index, colon and type */
180         {
181             *index = elem;
182             *index_len = cp - elem;
183             *type = cp+1;
184             *type_len = strlen(cp+1);
185         }
186     }
187     return 1;
188 }
189
190
191 int zebra_special_sort_fetch(ZebraHandle zh, zint sysno, ODR odr,
192                              const char *elemsetname,
193                              const Odr_oid *input_format,
194                              const Odr_oid **output_format,
195                              char **rec_bufp, int *rec_lenp)
196 {
197     const char *retrieval_index;
198     size_t retrieval_index_len; 
199     const char *retrieval_type;
200     size_t retrieval_type_len;
201     char retrieval_index_cstr[256];
202     char retrieval_type_cstr[256];
203     int ord;
204
205     /* only accept XML and SUTRS requests */
206     if (oid_oidcmp(input_format, yaz_oid_recsyn_xml) 
207         && oid_oidcmp(input_format, yaz_oid_recsyn_sutrs))
208     {
209         yaz_log(YLOG_WARN, "unsupported format for element set zebra::%s", 
210                 elemsetname);
211         *output_format = 0;
212         return YAZ_BIB1_NO_SYNTAXES_AVAILABLE_FOR_THIS_REQUEST;
213     }
214     
215     if (!parse_zebra_elem(elemsetname,
216                           &retrieval_index, &retrieval_index_len,
217                           &retrieval_type,  &retrieval_type_len))
218     {
219         return YAZ_BIB1_SPECIFIED_ELEMENT_SET_NAME_NOT_VALID_FOR_SPECIFIED_;
220     }
221     
222     if (retrieval_type_len == 0)
223         return -1;   /* must have a register type specified */
224     if (!retrieval_index_len ||
225         retrieval_index_len >= sizeof(retrieval_index_cstr)-1)
226     {
227         return YAZ_BIB1_SPECIFIED_ELEMENT_SET_NAME_NOT_VALID_FOR_SPECIFIED_;
228     }
229         
230     memcpy(retrieval_index_cstr, retrieval_index, retrieval_index_len);
231     retrieval_index_cstr[retrieval_index_len] = '\0';
232
233     memcpy(retrieval_type_cstr, retrieval_type, retrieval_type_len);
234     retrieval_type_cstr[retrieval_type_len] = '\0';
235
236     ord = zebraExplain_lookup_attr_str(zh->reg->zei,
237                                        zinfo_index_category_sort,
238                                        retrieval_type_cstr,
239                                        retrieval_index_cstr);
240     if (ord == -1)
241         return -1;  /* is not a sort index */
242     else
243     {
244         char dst_buf[IT_MAX_WORD];
245         char str[IT_MAX_WORD];
246         const char *index_type;
247         const char *db = 0;
248         const char *string_index = 0;
249         WRBUF wrbuf = wrbuf_alloc();
250         
251         zebra_sort_sysno(zh->reg->sort_index, sysno);
252         zebra_sort_type(zh->reg->sort_index, ord);
253         zebra_sort_read(zh->reg->sort_index, str);
254
255         zebraExplain_lookup_ord(zh->reg->zei, ord, &index_type, &db, &string_index);
256         
257         zebra_term_untrans(zh, index_type, dst_buf, str);
258
259         if (!oid_oidcmp(input_format, yaz_oid_recsyn_xml))
260         {
261             *output_format = yaz_oid_recsyn_xml;
262             wrbuf_printf(wrbuf, ZEBRA_XML_HEADER_STR
263                          " sysno=\"" ZINT_FORMAT "\""
264                          " set=\"zebra::index%s/\">\n",
265                          sysno, elemsetname);
266
267             wrbuf_printf(wrbuf, "  <index name=\"%s\"", 
268                          string_index);
269             wrbuf_printf(wrbuf, " type=\"%s\">", index_type);
270             wrbuf_xmlputs(wrbuf, dst_buf);
271             wrbuf_printf(wrbuf, "</index>\n");
272             wrbuf_printf(wrbuf, "</record>\n");
273         }
274         else if (!oid_oidcmp(input_format, yaz_oid_recsyn_sutrs))
275         {
276             *output_format = yaz_oid_recsyn_sutrs;
277             
278             wrbuf_printf(wrbuf, "%s %s %s\n", string_index, index_type,
279                          dst_buf);
280         }
281         *rec_lenp = wrbuf_len(wrbuf);
282         *rec_bufp = odr_malloc(odr, *rec_lenp);
283         memcpy(*rec_bufp, wrbuf_buf(wrbuf), *rec_lenp);
284         wrbuf_destroy(wrbuf);
285         return 0;
286     }
287 }
288                             
289 int zebra_special_index_fetch(ZebraHandle zh, zint sysno, ODR odr,
290                               Record rec,
291                               const char *elemsetname,
292                               const Odr_oid *input_format,
293                               const Odr_oid **output_format,
294                               char **rec_bufp, int *rec_lenp)
295 {
296     const char *retrieval_index;
297     size_t retrieval_index_len; 
298     const char *retrieval_type;
299     size_t retrieval_type_len;
300     zebra_rec_keys_t keys;
301     int ret_code = 0;
302     char retrieval_type_cstr[256];
303     
304     /* set output variables before processing possible error states */
305     /* *rec_lenp = 0; */
306
307     /* only accept XML and SUTRS requests */
308     if (oid_oidcmp(input_format, yaz_oid_recsyn_xml)
309         && oid_oidcmp(input_format, yaz_oid_recsyn_sutrs))
310     {
311         yaz_log(YLOG_WARN, "unsupported format for element set zebra::%s", 
312                 elemsetname);
313         *output_format = 0;
314         return YAZ_BIB1_NO_SYNTAXES_AVAILABLE_FOR_THIS_REQUEST;
315     }
316
317     if (!parse_zebra_elem(elemsetname,
318                      &retrieval_index, &retrieval_index_len,
319                      &retrieval_type,  &retrieval_type_len))
320         return YAZ_BIB1_SPECIFIED_ELEMENT_SET_NAME_NOT_VALID_FOR_SPECIFIED_;
321
322     if (retrieval_type_len)
323     {
324         memcpy(retrieval_type_cstr, retrieval_type, retrieval_type_len);
325         retrieval_type_cstr[retrieval_type_len] = '\0';
326     }
327     
328     if (retrieval_index_len)
329     {
330         char retrieval_index_cstr[256];
331
332         if (retrieval_index_len < sizeof(retrieval_index_cstr) -1)
333         {
334             memcpy(retrieval_index_cstr, retrieval_index, retrieval_index_len);
335             retrieval_index_cstr[retrieval_index_len] = '\0';
336             
337             if (zebraExplain_lookup_attr_str(zh->reg->zei,
338                                              zinfo_index_category_index,
339                                              (retrieval_type_len == 0 ? 0 : 
340                                               retrieval_type_cstr),
341                                              retrieval_index_cstr) == -1)
342                 return YAZ_BIB1_SPECIFIED_ELEMENT_SET_NAME_NOT_VALID_FOR_SPECIFIED_;
343         }
344     }
345
346     keys = zebra_rec_keys_open();
347     zebra_rec_keys_set_buf(keys, rec->info[recInfo_delKeys],
348                            rec->size[recInfo_delKeys], 0);
349
350     if (!zebra_rec_keys_rewind(keys))
351     {
352         ret_code = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
353     }
354     else
355     {
356         size_t slen;
357         const char *str;
358         struct it_key key_in;
359         WRBUF wrbuf = wrbuf_alloc();
360     
361         if (!oid_oidcmp(input_format, yaz_oid_recsyn_xml))
362         {
363             *output_format = input_format;
364             wrbuf_printf(wrbuf, ZEBRA_XML_HEADER_STR
365                          " sysno=\"" ZINT_FORMAT "\""
366                          " set=\"zebra::index%s/\">\n",
367                          sysno, elemsetname);
368         }
369         else if (!oid_oidcmp(input_format, yaz_oid_recsyn_sutrs))
370             *output_format = input_format;
371
372         while (zebra_rec_keys_read(keys, &str, &slen, &key_in))
373         {
374             int i;
375             int ord = CAST_ZINT_TO_INT(key_in.mem[0]);
376             const char *index_type;
377             const char *db = 0;
378             const char *string_index = 0;
379             size_t string_index_len;
380             char dst_buf[IT_MAX_WORD];
381             
382             zebraExplain_lookup_ord(zh->reg->zei, ord, &index_type, &db,
383                                     &string_index);
384             string_index_len = strlen(string_index);
385
386             /* process only if index is not defined, 
387                or if defined and matching */
388             if (retrieval_index == 0 
389                 || (string_index_len == retrieval_index_len 
390                     && !memcmp(string_index, retrieval_index,
391                                string_index_len)))
392             {
393                 /* process only if type is not defined, or is matching */
394                 if (retrieval_type == 0 
395                     || !strcmp(retrieval_type_cstr, index_type))
396                 {
397                     zebra_term_untrans(zh, index_type, dst_buf, str);
398                     if (strlen(dst_buf))
399                     {
400                         if (!oid_oidcmp(input_format, yaz_oid_recsyn_xml))
401                         {
402                             wrbuf_printf(wrbuf, "  <index name=\"%s\"", 
403                                          string_index);
404                             
405                             wrbuf_printf(wrbuf, " type=\"%s\"", index_type);
406                             
407                             wrbuf_printf(wrbuf, " seq=\"" ZINT_FORMAT "\">", 
408                                          key_in.mem[key_in.len -1]);
409                         
410                             wrbuf_xmlputs(wrbuf, dst_buf);
411                             wrbuf_printf(wrbuf, "</index>\n");
412                         }
413                         else 
414                         {
415                             wrbuf_printf(wrbuf, "%s ", string_index);
416                             
417                             wrbuf_printf(wrbuf, "%s", index_type);
418                             
419                             for (i = 1; i < key_in.len; i++)
420                                 wrbuf_printf(wrbuf, " " ZINT_FORMAT, 
421                                              key_in.mem[i]);
422                             
423                             wrbuf_printf(wrbuf, " %s", dst_buf);
424                         
425                             wrbuf_printf(wrbuf, "\n");
426                         }
427                     }
428                     
429                 }
430             }
431         }
432         if (!oid_oidcmp(input_format, yaz_oid_recsyn_xml))
433             wrbuf_printf(wrbuf, "</record>\n");
434         *rec_lenp = wrbuf_len(wrbuf);
435         *rec_bufp = odr_malloc(odr, *rec_lenp);
436         memcpy(*rec_bufp, wrbuf_buf(wrbuf), *rec_lenp);
437         wrbuf_destroy(wrbuf);
438     }
439     zebra_rec_keys_close(keys);
440     return ret_code;
441 }
442
443
444 static void retrieve_puts_attr(WRBUF wrbuf, const char *name,
445                                const char *value)
446 {
447     if (value)
448     {
449         wrbuf_printf(wrbuf, " %s=\"", name);
450         wrbuf_xmlputs(wrbuf, value);
451         wrbuf_printf(wrbuf, "\"");
452     }
453 }
454
455 static void retrieve_puts_attr_int(WRBUF wrbuf, const char *name,
456                                const int value)
457 {
458     wrbuf_printf(wrbuf, " %s=\"%i\"", name, value);
459 }
460
461 static void retrieve_puts_str(WRBUF wrbuf, const char *name,
462                                const char *value)
463 {
464     if (value)
465         wrbuf_printf(wrbuf, "%s %s\n", name, value);
466 }
467
468 static void retrieve_puts_int(WRBUF wrbuf, const char *name,
469                                const int value)
470 {
471     wrbuf_printf(wrbuf, "%s %i\n", name, value);
472 }
473
474
475 static void snippet_xml_record(ZebraHandle zh, WRBUF wrbuf, zebra_snippets *doc)
476 {
477     const zebra_snippet_word *doc_w;
478     int mark_state = 0;
479
480     wrbuf_printf(wrbuf, "%s>\n", ZEBRA_XML_HEADER_STR);
481     for (doc_w = zebra_snippets_constlist(doc); doc_w; doc_w = doc_w->next)
482     {
483         if (doc_w->mark)
484         {
485             const char *index_type;
486             const char *db = 0;
487             const char *string_index = 0;
488
489             zebraExplain_lookup_ord(zh->reg->zei, doc_w->ord, 
490                                     &index_type, &db, &string_index);
491
492             if (mark_state == 0)
493             {
494                 wrbuf_printf(wrbuf, "  <snippet name=\"%s\"",  string_index);
495                 wrbuf_printf(wrbuf, " type=\"%s\">", index_type);
496             }
497             if (doc_w->match)
498                 wrbuf_puts(wrbuf, "<s>");
499             /* not printing leading ws */
500             if (mark_state || !doc_w->ws || doc_w->match) 
501                 wrbuf_xmlputs(wrbuf, doc_w->term);
502             if (doc_w->match)
503                 wrbuf_puts(wrbuf, "</s>");
504         }
505         else if (mark_state == 1)
506         {
507             wrbuf_puts(wrbuf, "</snippet>\n");
508         }
509         mark_state = doc_w->mark;
510     }
511     if (mark_state == 1)
512     {
513         wrbuf_puts(wrbuf, "</snippet>\n");
514     }
515     wrbuf_printf(wrbuf, "</record>");
516 }
517
518 int zebra_get_rec_snippets(ZebraHandle zh, zint sysno,
519                            zebra_snippets *snippets)
520 {
521     int return_code = 0;
522     Record rec = rec_get(zh->reg->records, sysno);
523     if (!rec)
524     {
525         yaz_log(YLOG_WARN, "rec_get fail on sysno=" ZINT_FORMAT, sysno);
526         return_code = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
527     }
528     else
529     {
530         const char *file_type = rec->info[recInfo_fileType];
531         void *recTypeClientData;
532         RecType rt = recType_byName(zh->reg->recTypes, zh->res,
533                                     file_type, &recTypeClientData);
534
535         if (!rt)
536             return_code = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
537         else
538         {
539             struct ZebraRecStream stream;
540             return_code = zebra_create_record_stream(zh, &rec, &stream);
541             if (return_code == 0)
542             {
543                 extract_snippet(zh, snippets, &stream,
544                                 rt, recTypeClientData);
545
546                 stream.destroy(&stream);
547             }
548         }
549         rec_free(&rec);
550     }
551     return return_code;
552 }
553
554 static int snippet_fetch(ZebraHandle zh, const char *setname,
555                          zint sysno, ODR odr,
556                          const char *elemsetname,
557                          const Odr_oid *input_format,
558                          const Odr_oid **output_format,
559                          char **rec_bufp, int *rec_lenp)
560 {
561     zebra_snippets *rec_snippets = zebra_snippets_create();
562     int return_code = zebra_get_rec_snippets(zh, sysno, rec_snippets);
563
564     if (!return_code)
565     {
566         WRBUF wrbuf = wrbuf_alloc();
567         zebra_snippets *hit_snippet = zebra_snippets_create();
568
569         zebra_snippets_hit_vector(zh, setname, sysno, hit_snippet);
570
571 #if 0
572         /* for debugging purposes */
573         yaz_log(YLOG_LOG, "---------------------------");
574         yaz_log(YLOG_LOG, "REC SNIPPET:");
575         zebra_snippets_log(rec_snippet, YLOG_LOG, 1);
576         yaz_log(YLOG_LOG, "---------------------------");
577         yaz_log(YLOG_LOG, "HIT SNIPPET:");
578         zebra_snippets_log(hit_snippet, YLOG_LOG, 1);
579 #endif
580         
581         zebra_snippets_ring(rec_snippets, hit_snippet, 5, 5);
582         
583 #if 0
584         yaz_log(YLOG_LOG, "---------------------------");
585         yaz_log(YLOG_LOG, "RING SNIPPET:");
586         zebra_snippets_log(rec_snippets, YLOG_LOG, 1);
587 #endif
588         snippet_xml_record(zh, wrbuf, rec_snippets);
589         
590         *output_format = yaz_oid_recsyn_xml;
591         
592         if (return_code == 0)
593         {
594             *rec_lenp = wrbuf_len(wrbuf);
595             *rec_bufp = odr_strdup(odr, wrbuf_cstr(wrbuf));
596         }
597         wrbuf_destroy(wrbuf);
598         zebra_snippets_destroy(hit_snippet);
599     }
600     zebra_snippets_destroy(rec_snippets);
601     return return_code;
602 }
603
604 struct term_collect {
605     const char *term;
606     int oc;
607     zint set_occur;
608 };
609
610 zint freq_term(ZebraHandle zh, int ord, const char *term, RSET rset_set)
611 {
612     struct rset_key_control *kc = zebra_key_control_create(zh);
613     char ord_buf[IT_MAX_WORD];
614     int ord_len = key_SU_encode(ord, ord_buf);
615     char *info;
616     zint hits = 0;
617     NMEM nmem = nmem_create();
618     
619     strcpy(ord_buf + ord_len, term);
620     
621     info = dict_lookup(zh->reg->dict, ord_buf);
622     if (info)
623     {
624         ISAM_P isam_p;
625         RSET rsets[2], rset;
626         memcpy(&isam_p, info+1, sizeof(ISAM_P));
627         
628         rsets[0] = zebra_create_rset_isam(zh, nmem, kc, kc->scope, isam_p, 0);
629         rsets[1] = rset_dup(rset_set);
630         
631         rset = rset_create_and(nmem, kc, kc->scope, 2, rsets);
632
633         zebra_count_set(zh, rset, &hits, zh->approx_limit);
634
635         rset_delete(rsets[0]);
636         rset_delete(rset);
637     }
638     (*kc->dec)(kc);
639     nmem_destroy(nmem);
640     return hits;
641 }
642
643 int term_qsort_handle(const void *a, const void *b)
644 {
645     const struct term_collect *l = a;
646     const struct term_collect *r = b;
647     if (l->set_occur < r->set_occur)
648         return 1;
649     else if (l->set_occur > r->set_occur)
650         return -1;
651     else
652     {
653         const char *lterm = l->term ? l->term : "";
654         const char *rterm = r->term ? r->term : "";
655         return strcmp(lterm, rterm);
656     }
657 }
658
659 void term_collect_freq(ZebraHandle zh,
660                        struct term_collect *col, int no_terms_collect,
661                        int ord, RSET rset)
662 {
663     int i;
664     for (i = 0; i < no_terms_collect; i++)
665     {
666         if (col[i].term)
667             col[i].set_occur = freq_term(zh, ord, col[i].term, rset);
668     }
669     qsort(col, no_terms_collect, sizeof(*col), term_qsort_handle);
670 }
671
672 struct term_collect *term_collect_create(zebra_strmap_t sm, 
673                                          int no_terms_collect,
674                                          NMEM nmem)
675 {
676     const char *term;
677     void *data_buf;
678     size_t data_len;
679     zebra_strmap_it it;
680     struct term_collect *col = nmem_malloc(nmem, 
681                                            sizeof *col *no_terms_collect);
682     int i;
683     for (i = 0; i < no_terms_collect; i++)
684     {
685         col[i].term = 0;
686         col[i].oc = 0;
687         col[i].set_occur = 0;
688     }
689     /* iterate over terms and collect the most frequent ones */
690     it = zebra_strmap_it_create(sm);
691     while ((term = zebra_strmap_it_next(it, &data_buf, &data_len)))
692     {
693         /* invariant:
694            col[0] has lowest oc .  col[no_terms_collect-1] has highest oc */
695         int oc = *(int*) data_buf;
696         int j = 0;
697         /* insertion may be slow but terms terms will be "infrequent" and
698            thus number of iterations should be small below 
699         */
700         while (j < no_terms_collect && oc > col[j].oc)
701             j++;
702         if (j) 
703         {   /* oc <= col[j] and oc > col[j-1] */
704             --j;
705             memmove(col, col+1, sizeof(*col) * j);
706             col[j].term = term;
707             col[j].oc = oc;
708         }
709     }
710     zebra_strmap_it_destroy(it);
711     return col;
712 }
713
714 static ZEBRA_RES facet_fetch(ZebraHandle zh, const char *setname,
715                              ODR odr,
716                              const char *elemsetname,
717                              const Odr_oid *input_format,
718                              const Odr_oid **output_format,
719                              char **rec_bufp, int *rec_lenp)
720 {
721     zint *pos_array;
722     int i;
723     int num_recs = 10; /* number of records to analyze */
724     ZebraMetaRecord *poset;
725     ZEBRA_RES ret = ZEBRA_OK;
726     int *ord_array;
727     WRBUF wr = wrbuf_alloc();
728     int use_xml = 0;
729     
730     int no_ord = 0;
731     struct index_spec *spec, *spec_list;
732     int error;
733
734     /* see if XML is required for response */
735     if (oid_oidcmp(input_format, yaz_oid_recsyn_xml) == 0)
736         use_xml = 1;
737
738     spec_list = parse_index_spec(elemsetname, odr_getmem(odr), &error);
739               
740     if (!spec_list || error)
741     {
742         zebra_setError(
743             zh, 
744             YAZ_BIB1_SPECIFIED_ELEMENT_SET_NAME_NOT_VALID_FOR_SPECIFIED_,
745             0);
746         return ZEBRA_FAIL;
747     }          
748   
749     for (spec = spec_list; spec; spec = spec->next)
750     {
751         if (!spec->index_type)
752         {
753             zebra_setError(
754                 zh, 
755                 YAZ_BIB1_SPECIFIED_ELEMENT_SET_NAME_NOT_VALID_FOR_SPECIFIED_,
756                 0);
757             return ZEBRA_FAIL;
758         }
759         no_ord++;
760     }
761
762     ord_array = odr_malloc(odr, sizeof(*ord_array) * no_ord);
763
764     for (spec = spec_list, i = 0; spec; spec = spec->next, i++)
765     {
766         int ord = zebraExplain_lookup_attr_str(zh->reg->zei,
767                                                zinfo_index_category_index,
768                                                spec->index_type,
769                                                spec->index_name);
770         if (ord == -1)
771         {
772             zebra_setError(
773                 zh, 
774                 YAZ_BIB1_SPECIFIED_ELEMENT_SET_NAME_NOT_VALID_FOR_SPECIFIED_,
775                 0);
776             return ZEBRA_FAIL;
777         }
778         ord_array[i] = ord;
779     }
780     pos_array = (zint *) odr_malloc(odr, num_recs * sizeof(*pos_array));
781     for (i = 0; i < num_recs; i++)
782         pos_array[i] = i+1;
783     poset = zebra_meta_records_create(zh, setname, num_recs, pos_array);
784     if (!poset)
785     {
786         zebra_setError(zh, YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST,
787                        setname);
788         ret = ZEBRA_FAIL;
789     }
790     else
791     {
792         yaz_timing_t timing = yaz_timing_create();
793         zebra_strmap_t *map_array
794             = odr_malloc(odr, sizeof *map_array * no_ord);
795         for (i = 0; i < no_ord; i++)
796             map_array[i] = zebra_strmap_create();
797
798         for (i = 0; i < num_recs; i++)
799         {
800             int j;
801             zint sysnos[MAX_SYSNOS_PER_RECORD];
802             int no_sysnos = MAX_SYSNOS_PER_RECORD;
803             if (!poset[i].sysno)
804                 continue;
805             ret = zebra_result_recid_to_sysno(zh,  setname,
806                                               poset[i].sysno,
807                                               sysnos, &no_sysnos);
808             assert(no_sysnos > 0);
809             for (j = 0; j < no_sysnos; j++)
810             {
811                 size_t slen;
812                 const char *str;
813                 struct it_key key_in;
814                 Record rec = rec_get(zh->reg->records, sysnos[j]);
815                 zebra_rec_keys_t keys = zebra_rec_keys_open();
816                 zebra_rec_keys_set_buf(keys, rec->info[recInfo_delKeys],
817                                        rec->size[recInfo_delKeys], 0);
818                 
819                 if (zebra_rec_keys_rewind(keys))
820                 {
821                     while (zebra_rec_keys_read(keys, &str, &slen, &key_in))
822                     {
823                         int i;
824                         struct index_spec *spec;
825                         for (spec = spec_list, i = 0; i < no_ord; 
826                              i++, spec = spec->next)
827                         {
828                             int ord = CAST_ZINT_TO_INT(key_in.mem[0]);
829                             if (ord == ord_array[i] && 
830                                 str[0] != FIRST_IN_FIELD_CHAR)
831                             {
832                                 int *freq;
833                                 zebra_strmap_t sm = map_array[i];
834                                 
835                                 freq = zebra_strmap_lookup(sm, str, 0, 0);
836                                 if (freq)
837                                     (*freq)++;
838                                 else
839                                 {
840                                     int v = 1;
841                                     zebra_strmap_add(sm, str, &v, sizeof v);
842                                 }
843                             }
844                         }
845                     }
846                 }
847                 zebra_rec_keys_close(keys);
848                 rec_free(&rec);
849             }
850         }
851         yaz_timing_stop(timing);
852         yaz_log(YLOG_LOG, "facet first phase real=%4.2f",
853                 yaz_timing_get_real(timing));
854         yaz_timing_start(timing);
855         if (use_xml)
856             wrbuf_puts(wr, "<facets>\n");
857         for (spec = spec_list, i = 0; i < no_ord; i++, spec = spec->next)
858         {
859             int j;
860             NMEM nmem = nmem_create();
861             struct term_collect *col;
862             int no_collect_terms = 20;
863
864             if (spec->extra)
865                 no_collect_terms = atoi(spec->extra);
866             if (no_collect_terms < 1)
867                 no_collect_terms = 1;
868             col = term_collect_create(map_array[i], no_collect_terms, nmem);
869             term_collect_freq(zh, col, no_collect_terms, ord_array[i],
870                               resultSetRef(zh, setname));
871             
872             if (use_xml)
873                 wrbuf_printf(wr, "  <facet type=\"%s\" index=\"%s\">\n",
874                              spec->index_type, spec->index_name);
875             else
876                 wrbuf_printf(wr, "facet %s %s\n",
877                              spec->index_type, spec->index_name);
878             for (j = 0; j < no_collect_terms; j++)
879             {
880                 if (col[j].term)
881                 {
882                     char dst_buf[IT_MAX_WORD];
883                     zebra_term_untrans(zh, spec->index_type, dst_buf, col[j].term);
884                     if (use_xml)
885                     {
886                         wrbuf_printf(wr, "    <term coccur=\"%d\"", col[j].oc);
887                         if (col[j].set_occur)
888                             wrbuf_printf(wr, " occur=\"" ZINT_FORMAT "\"", 
889                                          col[j].set_occur);
890                         wrbuf_printf(wr, ">");
891                         wrbuf_xmlputs(wr, dst_buf);
892                         wrbuf_printf(wr, "</term>\n");
893                     }
894                     else
895                     {
896                         wrbuf_printf(wr, "term %d", col[j].oc);
897                         if (col[j].set_occur)
898                             wrbuf_printf(wr, " " ZINT_FORMAT, 
899                                          col[j].set_occur);
900                         wrbuf_printf(wr, ": %s\n", dst_buf);
901                     }
902                 }
903             }
904             if (use_xml)
905                 wrbuf_puts(wr, "  </facet>\n");
906             nmem_destroy(nmem);
907         }
908         if (use_xml)
909             wrbuf_puts(wr, "</facets>\n");
910         for (i = 0; i < no_ord; i++)
911             zebra_strmap_destroy(map_array[i]);
912         yaz_timing_stop(timing);
913         yaz_log(YLOG_LOG, "facet second phase real=%4.2f",
914                 yaz_timing_get_real(timing));
915         yaz_timing_destroy(&timing);
916     }
917     *rec_bufp = odr_strdup(odr, wrbuf_cstr(wr));
918     wrbuf_destroy(wr);
919     *rec_lenp = strlen(*rec_bufp);
920     *output_format = yaz_oid_recsyn_xml;
921
922     zebra_meta_records_destroy(zh, poset, num_recs);
923     return ret;
924 }
925
926 int zebra_special_fetch(ZebraHandle zh, const char *setname,
927                         zint sysno, int score, ODR odr,
928                         const char *elemsetname,
929                         const Odr_oid *input_format,
930                         const Odr_oid **output_format,
931                         char **rec_bufp, int *rec_lenp)
932 {
933     Record rec;
934     
935     /* set output variables before processing possible error states */
936     /* *rec_lenp = 0; */
937
938     if (elemsetname && 0 == strncmp(elemsetname, "facet", 5))
939     {
940         return facet_fetch(zh, setname, odr,
941                            elemsetname + 5,
942                            input_format, output_format,
943                            rec_bufp, rec_lenp);
944     }
945
946     if (elemsetname && 0 == strcmp(elemsetname, "snippet"))
947     {
948         return snippet_fetch(zh, setname, sysno, odr,
949                              elemsetname + 7,
950                              input_format, output_format,
951                              rec_bufp, rec_lenp);
952     }
953
954     /* processing zebra::meta::sysno elemset without fetching binary data */
955     if (elemsetname && 0 == strcmp(elemsetname, "meta::sysno"))
956     {
957         int ret = 0;
958         WRBUF wrbuf = wrbuf_alloc();
959         if (!oid_oidcmp(input_format, yaz_oid_recsyn_sutrs))
960         {
961             wrbuf_printf(wrbuf, ZINT_FORMAT, sysno);
962             *output_format = input_format;
963         } 
964         else if (!oid_oidcmp(input_format, yaz_oid_recsyn_xml))
965         {
966             wrbuf_printf(wrbuf, ZEBRA_XML_HEADER_STR
967                          " sysno=\"" ZINT_FORMAT "\"/>\n",
968                          sysno);
969             *output_format = input_format;
970         }
971         *rec_lenp = wrbuf_len(wrbuf);
972         if (*rec_lenp)
973             *rec_bufp = odr_strdup(odr, wrbuf_cstr(wrbuf));
974         else
975             ret = YAZ_BIB1_NO_SYNTAXES_AVAILABLE_FOR_THIS_REQUEST;
976         wrbuf_destroy(wrbuf);
977         return ret;
978     }
979
980     /* processing special elementsetname zebra::index:: for sort elements */
981     if (elemsetname && 0 == strncmp(elemsetname, "index", 5))
982     {
983         int ret = zebra_special_sort_fetch(zh, sysno, odr,
984                                            elemsetname + 5,
985                                            input_format, output_format,
986                                            rec_bufp, rec_lenp);
987         if (ret != -1)
988             return ret;
989         /* not a sort index so we continue to get the full record */
990     }
991
992
993     /* fetching binary record up for all other display elementsets */
994     rec = rec_get(zh->reg->records, sysno);
995     if (!rec)
996     {
997         yaz_log(YLOG_WARN, "rec_get fail on sysno=" ZINT_FORMAT, sysno);
998         return YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
999     }
1000
1001     /* processing special elementsetnames zebra::data */    
1002     if (elemsetname && 0 == strcmp(elemsetname, "data"))
1003     {
1004         struct ZebraRecStream stream;
1005         RecordAttr *recordAttr = rec_init_attr(zh->reg->zei, rec); 
1006         zebra_create_record_stream(zh, &rec, &stream);
1007         *output_format = input_format;
1008         *rec_lenp = recordAttr->recordSize;
1009         *rec_bufp = (char *) odr_malloc(odr, *rec_lenp);
1010         stream.readf(&stream, *rec_bufp, *rec_lenp);
1011         stream.destroy(&stream);
1012         rec_free(&rec);
1013         return 0;
1014     }
1015
1016     /* only accept XML and SUTRS requests from now */
1017     if (oid_oidcmp(input_format, yaz_oid_recsyn_xml)
1018         && oid_oidcmp(input_format, yaz_oid_recsyn_sutrs))
1019     {
1020         yaz_log(YLOG_WARN, "unsupported format for element set zebra::%s", 
1021                 elemsetname);
1022         return YAZ_BIB1_NO_SYNTAXES_AVAILABLE_FOR_THIS_REQUEST;
1023     }
1024     
1025
1026     /* processing special elementsetnames zebra::meta:: */
1027     if (elemsetname && 0 == strcmp(elemsetname, "meta"))
1028     {
1029         int ret = 0;
1030         WRBUF wrbuf = wrbuf_alloc();
1031         RecordAttr *recordAttr = rec_init_attr(zh->reg->zei, rec); 
1032
1033         if (!oid_oidcmp(input_format, yaz_oid_recsyn_xml))
1034         {
1035             *output_format = input_format;
1036             
1037             wrbuf_printf(wrbuf, ZEBRA_XML_HEADER_STR
1038                          " sysno=\"" ZINT_FORMAT "\"", sysno);
1039             retrieve_puts_attr(wrbuf, "base", rec->info[recInfo_databaseName]);
1040             retrieve_puts_attr(wrbuf, "file", rec->info[recInfo_filename]);
1041             retrieve_puts_attr(wrbuf, "type", rec->info[recInfo_fileType]);
1042             if (score >= 0)
1043                 retrieve_puts_attr_int(wrbuf, "score", score);
1044            
1045             wrbuf_printf(wrbuf,
1046                          " rank=\"" ZINT_FORMAT "\""
1047                          " size=\"%i\""
1048                          " set=\"zebra::%s\"/>\n",
1049                          recordAttr->staticrank,
1050                          recordAttr->recordSize,
1051                          elemsetname);
1052         }
1053         else if (!oid_oidcmp(input_format, yaz_oid_recsyn_sutrs))
1054         {
1055             *output_format = input_format;
1056             wrbuf_printf(wrbuf, "sysno " ZINT_FORMAT "\n", sysno);
1057             retrieve_puts_str(wrbuf, "base", rec->info[recInfo_databaseName]);
1058             retrieve_puts_str(wrbuf, "file", rec->info[recInfo_filename]);
1059             retrieve_puts_str(wrbuf, "type", rec->info[recInfo_fileType]);
1060             if (score >= 0)
1061                 retrieve_puts_int(wrbuf, "score", score);
1062
1063             wrbuf_printf(wrbuf,
1064                          "rank " ZINT_FORMAT "\n"
1065                          "size %i\n"
1066                          "set zebra::%s\n",
1067                          recordAttr->staticrank,
1068                          recordAttr->recordSize,
1069                          elemsetname);
1070         }
1071         *rec_lenp = wrbuf_len(wrbuf);
1072         if (*rec_lenp)
1073             *rec_bufp = odr_strdup(odr, wrbuf_cstr(wrbuf));
1074         else
1075             ret = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
1076
1077         wrbuf_destroy(wrbuf);
1078         rec_free(&rec);
1079         return ret;
1080     }
1081
1082     /* processing special elementsetnames zebra::index:: */
1083     if (elemsetname && 0 == strncmp(elemsetname, "index", 5))
1084     {
1085         int ret = zebra_special_index_fetch(zh, sysno, odr, rec,
1086                                             elemsetname + 5,
1087                                             input_format, output_format,
1088                                             rec_bufp, rec_lenp);
1089         
1090         rec_free(&rec);
1091         return ret;
1092     }
1093
1094     if (rec)
1095         rec_free(&rec);
1096     return YAZ_BIB1_SPECIFIED_ELEMENT_SET_NAME_NOT_VALID_FOR_SPECIFIED_;
1097 }
1098
1099                           
1100 int zebra_record_fetch(ZebraHandle zh, const char *setname,
1101                        zint sysno, int score,
1102                        ODR odr,
1103                        const Odr_oid *input_format, Z_RecordComposition *comp,
1104                        const Odr_oid **output_format,
1105                        char **rec_bufp, int *rec_lenp, char **basenamep,
1106                        char **addinfo)
1107 {
1108     Record rec;
1109     char *fname, *file_type, *basename;
1110     const char *elemsetname;
1111     struct ZebraRecStream stream;
1112     RecordAttr *recordAttr;
1113     void *clientData;
1114     int return_code = 0;
1115     zint sysnos[MAX_SYSNOS_PER_RECORD];
1116     int no_sysnos = MAX_SYSNOS_PER_RECORD;
1117     ZEBRA_RES res;
1118
1119     res = zebra_result_recid_to_sysno(zh, setname, sysno, sysnos, &no_sysnos);
1120     if (res != ZEBRA_OK)
1121         return ZEBRA_FAIL;
1122
1123     sysno = sysnos[0];
1124     *basenamep = 0;
1125     *addinfo = 0;
1126     elemsetname = yaz_get_esn(comp);
1127
1128     /* processing zebra special elementset names of form 'zebra:: */
1129     if (elemsetname && 0 == strncmp(elemsetname, "zebra::", 7))
1130         return  zebra_special_fetch(zh, setname, sysno, score, odr,
1131                                     elemsetname + 7,
1132                                     input_format, output_format,
1133                                     rec_bufp, rec_lenp);
1134
1135
1136     /* processing all other element set names */
1137     rec = rec_get(zh->reg->records, sysno);
1138     if (!rec)
1139     {
1140         yaz_log(YLOG_WARN, "rec_get fail on sysno=" ZINT_FORMAT, sysno);
1141         *basenamep = 0;
1142         return YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
1143     }
1144
1145
1146     recordAttr = rec_init_attr(zh->reg->zei, rec);
1147
1148     file_type = rec->info[recInfo_fileType];
1149     fname = rec->info[recInfo_filename];
1150     basename = rec->info[recInfo_databaseName];
1151     *basenamep = (char *) odr_malloc(odr, strlen(basename)+1);
1152     strcpy(*basenamep, basename);
1153
1154     yaz_log(YLOG_DEBUG, "retrieve localno=" ZINT_FORMAT " score=%d",
1155             sysno, score);
1156
1157     return_code = zebra_create_record_stream(zh, &rec, &stream);
1158
1159     if (rec)
1160     {
1161         RecType rt;
1162         struct recRetrieveCtrl retrieveCtrl;
1163
1164         retrieveCtrl.stream = &stream;
1165         retrieveCtrl.fname = fname;
1166         retrieveCtrl.localno = sysno;
1167         retrieveCtrl.staticrank = recordAttr->staticrank;
1168         retrieveCtrl.score = score;
1169         retrieveCtrl.recordSize = recordAttr->recordSize;
1170         retrieveCtrl.odr = odr;
1171         retrieveCtrl.input_format = retrieveCtrl.output_format = input_format;
1172         retrieveCtrl.comp = comp;
1173         retrieveCtrl.encoding = zh->record_encoding;
1174         retrieveCtrl.diagnostic = 0;
1175         retrieveCtrl.addinfo = 0;
1176         retrieveCtrl.dh = zh->reg->dh;
1177         retrieveCtrl.res = zh->res;
1178         retrieveCtrl.rec_buf = 0;
1179         retrieveCtrl.rec_len = -1;
1180
1181         if (!(rt = recType_byName(zh->reg->recTypes, zh->res,
1182                                   file_type, &clientData)))
1183         {
1184             char addinfo_str[100];
1185
1186             sprintf(addinfo_str, "Could not handle record type %.40s",
1187                     file_type);
1188                     
1189             *addinfo = odr_strdup(odr, addinfo_str);
1190             return_code = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
1191         }
1192         else
1193         {
1194             (*rt->retrieve)(clientData, &retrieveCtrl);
1195             return_code = retrieveCtrl.diagnostic;
1196
1197             *output_format = retrieveCtrl.output_format;
1198             *rec_bufp = (char *) retrieveCtrl.rec_buf;
1199             *rec_lenp = retrieveCtrl.rec_len;
1200             *addinfo = retrieveCtrl.addinfo;
1201         }
1202
1203         stream.destroy(&stream);
1204         rec_free(&rec);
1205     }
1206
1207     return return_code;
1208 }
1209
1210 /*
1211  * Local variables:
1212  * c-basic-offset: 4
1213  * indent-tabs-mode: nil
1214  * End:
1215  * vim: shiftwidth=4 tabstop=8 expandtab
1216  */
1217