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