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