scan: Fix first-in-field term skipping
[idzebra-moved-to-github.git] / index / rpnscan.c
1 /* This file is part of the Zebra server.
2    Copyright (C) 1994-2011 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 #ifdef WIN32
23 #include <io.h>
24 #endif
25 #if HAVE_UNISTD_H
26 #include <unistd.h>
27 #endif
28 #include <ctype.h>
29
30 #include <yaz/diagbib1.h>
31 #include "index.h"
32 #include <zebra_xpath.h>
33 #include <yaz/wrbuf.h>
34 #include <attrfind.h>
35 #include <charmap.h>
36 #include <rset.h>
37 #include <yaz/oid_db.h>
38
39 #define RPN_MAX_ORDS 32
40
41 /* convert APT SCAN term to internal cmap */
42 static ZEBRA_RES trans_scan_term(ZebraHandle zh, Z_AttributesPlusTerm *zapt,
43                                  char *termz, zebra_map_t zm)
44 {
45     char term_utf8[IT_MAX_WORD];
46
47     if (zapt_term_to_utf8(zh, zapt, term_utf8) == ZEBRA_FAIL)
48         return ZEBRA_FAIL;    /* error */
49     else if (zebra_maps_is_icu(zm))
50     {
51         const char *res_buf;
52         size_t res_len;
53         zebra_map_tokenize_start(zm, term_utf8, strlen(term_utf8));
54         
55         if (zebra_map_tokenize_next(zm, &res_buf, &res_len, 0, 0))
56         {
57             memcpy(termz, res_buf, res_len);
58             termz[res_len] = '\0';
59         }
60         else
61             termz[0] = '\0';
62     }
63     else
64     {
65         const char **map;
66         const char *cp = (const char *) term_utf8;
67         const char *cp_end = cp + strlen(cp);
68         const char *src;
69         int i = 0;
70         const char *space_map = NULL;
71         int len;
72             
73         while ((len = (cp_end - cp)) > 0)
74         {
75             map = zebra_maps_input(zm, &cp, len, 0);
76             if (**map == *CHR_SPACE)
77                 space_map = *map;
78             else
79             {
80                 if (i && space_map)
81                     for (src = space_map; *src; src++)
82                         termz[i++] = *src;
83                 space_map = NULL;
84                 for (src = *map; *src; src++)
85                     termz[i++] = *src;
86             }
87         }
88         termz[i] = '\0';
89     }
90     return ZEBRA_OK;
91 }
92
93 static void get_first_snippet_from_rset(ZebraHandle zh, 
94                                         RSET rset, zebra_snippets *snippets, 
95                                         zint *sysno)
96 {
97     struct it_key key;
98     RSFD rfd;
99     TERMID termid;
100     size_t sysno_mem_index = 0;
101
102     if (zh->m_staticrank)
103         sysno_mem_index = 1;
104
105     yaz_log(YLOG_DEBUG, "get_first_snippet_from_rset");
106
107     rfd = rset_open(rset, RSETF_READ);
108     *sysno = 0;
109     while (rset_read(rfd, &key, &termid))
110     {
111         if (key.mem[sysno_mem_index] != *sysno)
112         {
113             if (*sysno)
114                 break;
115             *sysno = key.mem[sysno_mem_index];
116         }
117         if (termid)
118         {
119             struct ord_list *ol;
120             for (ol = termid->ol; ol; ol = ol->next)
121             {
122                 zebra_snippets_append(snippets, key.mem[key.len-1], 0,
123                                       ol->ord, termid->name);
124             }
125         }
126     }
127     rset_close(rfd);
128 }
129
130 struct scan2_info_entry {
131     WRBUF term;
132     char prefix[20];
133     ISAM_P isam_p;
134     int pos_to_save;
135     int ord;
136 };
137
138 static int scan_handle2(char *name, const char *info, int pos, void *client)
139 {
140     int len_prefix;
141     struct scan2_info_entry *scan_info = (struct scan2_info_entry *) client;
142
143     if (scan_info->pos_to_save != pos)
144         return 0;
145
146     len_prefix = strlen(scan_info->prefix);
147     if (memcmp(name, scan_info->prefix, len_prefix))
148         return 1;
149     wrbuf_rewind(scan_info->term);
150     wrbuf_puts(scan_info->term, name+len_prefix);
151
152     assert(*info == sizeof(ISAM_P));
153     memcpy(&scan_info->isam_p, info+1, sizeof(ISAM_P));
154     return 0;
155 }
156
157
158 static int scan_save_set(ZebraHandle zh, ODR stream, NMEM nmem,
159                          struct rset_key_control *kc,
160                          Z_AttributesPlusTerm *zapt,
161                          RSET limit_set,
162                          const char *term, 
163                          const char *index_type,
164                          struct scan2_info_entry *ar, int ord_no,
165                          ZebraScanEntry *glist, int pos)
166 {
167     int i;
168     RSET rset = 0;
169     zint approx_limit = zh->approx_limit;
170     AttrType global_hits_limit_attr;
171     int l;
172     attr_init_APT(&global_hits_limit_attr, zapt, 12);
173             
174     l = attr_find(&global_hits_limit_attr, NULL);
175     if (l != -1)
176         approx_limit = l;
177     
178     for (i = 0; i < ord_no; i++)
179     {
180         if (ar[i].isam_p && strcmp(wrbuf_cstr(ar[i].term), term) == 0)
181         {
182             if (strcmp(term, FIRST_IN_FIELD_STR))
183             {
184                 struct ord_list *ol = ord_list_create(nmem);
185                 RSET rset_t;
186                 
187                 ol = ord_list_append(nmem, ol, ar[i].ord);
188                 
189                 assert(ol);
190                 rset_t = rset_trunc(
191                     zh, &ar[i].isam_p, 1,
192                     wrbuf_buf(ar[i].term), wrbuf_len(ar[i].term),
193                     NULL, 1, zapt->term->which, nmem, 
194                     kc, kc->scope, ol, index_type, 
195                     0 /* hits_limit_value */,
196                     0 /* term_ref_id_str */);
197                 if (!rset)
198                     rset = rset_t;
199                 else
200                 {
201                     RSET rsets[2];
202                     
203                     rsets[0] = rset;
204                     rsets[1] = rset_t;
205                     rset = rset_create_or(nmem, kc, kc->scope, 0 /* termid */,
206                                           2, rsets);
207                 }
208             }
209             ar[i].isam_p = 0;
210         }
211     }
212     if (rset)
213     {
214         zint count;
215         /* merge with limit_set if given */
216         if (limit_set)
217         {
218             RSET rsets[2];
219             rsets[0] = rset;
220             rsets[1] = rset_dup(limit_set);
221             
222             rset = rset_create_and(nmem, kc, kc->scope, 2, rsets);
223         }
224         /* count it */
225         zebra_count_set(zh, rset, &count, approx_limit);
226
227         if (pos != -1)
228         {
229             zint sysno;
230             zebra_snippets *hit_snippets = zebra_snippets_create();
231
232             glist[pos].term = 0;
233             glist[pos].display_term = 0;
234             
235             get_first_snippet_from_rset(zh, rset, hit_snippets, &sysno);
236             if (sysno)
237             {
238                 zebra_snippets *rec_snippets = zebra_snippets_create();
239                 int code = zebra_get_rec_snippets(zh, sysno, rec_snippets);
240                 if (code == 0)
241                 {
242                     const struct zebra_snippet_word *w = 
243                         zebra_snippets_lookup(rec_snippets, hit_snippets);
244                     if (w)
245                     {
246                         glist[pos].display_term = odr_strdup(stream, w->term);
247                     }
248                     else
249                     {
250                         yaz_log(YLOG_WARN, "zebra_snippets_lookup failed for pos=%d", pos);
251                     }
252                 }
253                 zebra_snippets_destroy(rec_snippets);
254             }
255             if (zebra_term_untrans_iconv(zh, stream->mem, index_type,
256                                          &glist[pos].term, term))
257             {
258                 /* failed.. use display_term instead (which could be 0) */
259                 glist[pos].term = glist[pos].display_term;
260             }
261
262             if (!glist[pos].term)
263             {
264                 yaz_log(YLOG_WARN, "Could not generate scan term for pos=%d",
265                         pos);
266                 glist[pos].term = "None";
267             }
268             glist[pos].occurrences = count;
269             zebra_snippets_destroy(hit_snippets);
270         }
271         rset_delete(rset);
272         if (count > 0)
273             return 1;
274         else
275             return 0;
276     }
277     return 0;
278 }
279
280 static ZEBRA_RES rpn_scan_norm(ZebraHandle zh, ODR stream, NMEM nmem,
281                                struct rset_key_control *kc,
282                                Z_AttributesPlusTerm *zapt,
283                                int *position, int *num_entries, 
284                                ZebraScanEntry **list,
285                                int *is_partial, RSET limit_set,
286                                const char *index_type,
287                                int ord_no, int *ords)
288 {
289     struct scan2_info_entry *ar = nmem_malloc(nmem, sizeof(*ar) * ord_no);
290     struct rpn_char_map_info rcmi;
291     zebra_map_t zm = zebra_map_get_or_add(zh->reg->zebra_maps, index_type);
292     int i, dif;
293     int after_pos;
294     int pos = 0;
295
296     ZebraScanEntry *glist = (ZebraScanEntry *)
297         odr_malloc(stream, *num_entries * sizeof(*glist));
298
299     *is_partial = 0;
300     if (*position > *num_entries+1)
301     {
302         *is_partial = 1;
303         *position = 1;
304         *num_entries = 0;
305         return ZEBRA_OK;
306     }
307     rpn_char_map_prepare(zh->reg, zm, &rcmi);
308
309     for (i = 0; i < ord_no; i++)
310         ar[i].term = wrbuf_alloc();
311
312     for (i = 0; i < ord_no; i++)
313     {
314         char termz[IT_MAX_WORD+20];
315         int prefix_len = 0;
316         
317         prefix_len = key_SU_encode(ords[i], termz);
318         termz[prefix_len] = 0;
319         strcpy(ar[i].prefix, termz);
320         
321         if (trans_scan_term(zh, zapt, termz+prefix_len, zm) == 
322             ZEBRA_FAIL)
323         {
324             for (i = 0; i < ord_no; i++)
325                 wrbuf_destroy(ar[i].term);
326             return ZEBRA_FAIL;
327         }
328         wrbuf_rewind(ar[i].term);
329         wrbuf_puts(ar[i].term, termz + prefix_len);
330         ar[i].isam_p = 0;
331         ar[i].ord = ords[i];
332     }
333     /** deal with terms before position .. */
334     /* the glist index starts at zero (unlike scan positions */
335     for (pos = *position-2; pos >= 0; )
336     {
337         const char *hi = 0;
338
339         /* scan on all maximum terms */
340         for (i = 0; i < ord_no; i++)
341         {
342             if (ar[i].isam_p == 0)
343             {
344                 char termz[IT_MAX_WORD+20];
345                 int before = 1;
346                 int after = 0;
347
348                 ar[i].pos_to_save = -1;
349
350                 strcpy(termz, ar[i].prefix);
351                 strcat(termz, wrbuf_cstr(ar[i].term));
352                 dict_scan(zh->reg->dict, termz, &before, &after,
353                           ar+i, scan_handle2);
354             }
355         }
356         /* get maximum after scan */
357         for (i = 0; i < ord_no; i++)
358         {
359             if (ar[i].isam_p 
360                 && (hi == 0 || strcmp(wrbuf_cstr(ar[i].term), hi) > 0))
361                 hi = wrbuf_cstr(ar[i].term);
362         }
363         if (!hi)
364             break;
365         if (scan_save_set(zh, stream, nmem, kc, zapt, limit_set, hi,
366                           index_type, ar, ord_no, glist,
367                           (pos >= 0 && pos < *num_entries) ? pos : -1))
368             --pos;
369     }
370     /* see if we got all terms before.. */
371     dif = 1 + pos;
372     if (dif > 0)
373     {
374         /* did not get all terms; adjust the real position and reduce
375            number of entries */
376         glist = glist + dif;
377         *num_entries -= dif;
378         *position -= dif;
379         *is_partial = 1;
380     }
381     for (i = 0; i < ord_no; i++)
382     {
383         char termz[IT_MAX_WORD+20];
384         int prefix_len = 0;
385         
386         prefix_len = key_SU_encode(ords[i], termz);
387         termz[prefix_len] = 0;
388         strcpy(ar[i].prefix, termz);
389         
390         if (trans_scan_term(zh, zapt, termz+prefix_len, zm) == 
391             ZEBRA_FAIL)
392             return ZEBRA_FAIL;
393         wrbuf_rewind(ar[i].term);
394         wrbuf_puts(ar[i].term, termz + prefix_len);
395         ar[i].isam_p = 0;
396         ar[i].ord = ords[i];
397     }
398
399     after_pos = 1;  /* immediate term first.. */
400     for (pos = *position-1; pos < *num_entries; )
401     {
402         const char *lo = 0;
403
404         /* scan on all minimum terms */
405         for (i = 0; i < ord_no; i++)
406         {
407             if (ar[i].isam_p == 0)
408             {
409                 char termz[IT_MAX_WORD+20];
410                 int before = 0;
411                 int after = after_pos;
412
413                 ar[i].pos_to_save = 1;
414
415                 strcpy(termz, ar[i].prefix);
416                 strcat(termz, wrbuf_cstr(ar[i].term));
417                 dict_scan(zh->reg->dict, termz, &before, &after,
418                           ar+i, scan_handle2);
419             }
420         }
421         after_pos = 2;  /* next round we grab following term */
422
423         /* get minimum after scan */
424         for (i = 0; i < ord_no; i++)
425         {
426             if (ar[i].isam_p 
427                 && (lo == 0 || strcmp(wrbuf_cstr(ar[i].term), lo) < 0))
428                 lo = wrbuf_cstr(ar[i].term);
429         }
430         if (!lo)
431             break;
432         if (scan_save_set(zh, stream, nmem, kc, zapt, limit_set, lo,
433                           index_type, ar, ord_no, glist,
434                           (pos >= 0 && pos < *num_entries) ? pos : -1))
435             pos++;
436
437     }
438     if (pos != *num_entries)
439     {
440         if (pos >= 0)
441             *num_entries = pos;
442         else
443             *num_entries = 0;
444         *is_partial = 1;
445     }
446
447     *list = glist;
448
449     for (i = 0; i < ord_no; i++)
450         wrbuf_destroy(ar[i].term);
451
452     return ZEBRA_OK;
453 }
454
455 struct scan1_info_entry {
456     char *term;
457     ISAM_P isam_p;
458 };
459
460 struct scan_info {
461     struct scan1_info_entry *list;
462     ODR odr;
463     int before, after;
464     char prefix[20];
465 };
466
467 ZEBRA_RES rpn_scan(ZebraHandle zh, ODR stream, Z_AttributesPlusTerm *zapt,
468                    const Odr_oid *attributeset,
469                    int num_bases, char **basenames,
470                    int *position, int *num_entries, ZebraScanEntry **list,
471                    int *is_partial, const char *set_name)
472 {
473     int base_no;
474     int ords[RPN_MAX_ORDS], ord_no = 0;
475
476     const char *index_type;
477     char *search_type = NULL;
478     char rank_type[128];
479     int complete_flag;
480     int sort_flag;
481     NMEM nmem;
482     ZEBRA_RES res;
483     struct rset_key_control *kc = 0;
484     RSET limit_set = 0;
485
486     *list = 0;
487     *is_partial = 0;
488
489     if (!attributeset)
490         attributeset = yaz_oid_attset_bib_1;
491
492     if (!set_name)
493     {
494         /* see if there is a @attr 8=set */
495         AttrType termset;
496         int termset_value_numeric;
497         const char *termset_value_string = 0;
498         attr_init_APT(&termset, zapt, 8);
499         termset_value_numeric =
500             attr_find_ex(&termset, NULL, &termset_value_string);
501         if (termset_value_numeric != -1)
502         {
503             if (termset_value_numeric != -2)
504             {
505                 char resname[32];
506                 sprintf(resname, "%d", termset_value_numeric);
507                 set_name = odr_strdup(stream, resname); 
508             }
509             else
510                 set_name = odr_strdup(stream, termset_value_string);
511         }
512     }
513
514     if (set_name)
515     {
516         limit_set = resultSetRef(zh, set_name);
517         
518         if (!limit_set)
519         {
520             zebra_setError(zh, 
521                            YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST,
522                            set_name);
523             return ZEBRA_FAIL;
524         }
525     }
526
527     yaz_log(YLOG_DEBUG, "position = %d, num = %d",
528             *position, *num_entries);
529         
530     if (zebra_maps_attr(zh->reg->zebra_maps, zapt, &index_type, &search_type,
531                         rank_type, &complete_flag, &sort_flag))
532     {
533         *num_entries = 0;
534         zebra_setError(zh, YAZ_BIB1_UNSUPP_ATTRIBUTE_TYPE, 0);
535         return ZEBRA_FAIL;
536     }
537     if (num_bases > RPN_MAX_ORDS)
538     {
539         zebra_setError(zh, YAZ_BIB1_TOO_MANY_DATABASES_SPECIFIED, 0);
540         return ZEBRA_FAIL;
541     }
542     for (base_no = 0; base_no < num_bases; base_no++)
543     {
544         int ord;
545
546         if (zebraExplain_curDatabase(zh->reg->zei, basenames[base_no]))
547         {
548             zebra_setError(zh, YAZ_BIB1_DATABASE_UNAVAILABLE,
549                            basenames[base_no]);
550             *num_entries = 0;
551             return ZEBRA_FAIL;
552         }
553         if (zebra_apt_get_ord(zh, zapt, index_type, 0, attributeset, &ord) 
554             != ZEBRA_OK)
555             continue;
556         ords[ord_no++] = ord;
557     }
558     if (ord_no == 0)
559     {
560         *num_entries = 0; /* zebra_apt_get_ord should set error reason */
561         return ZEBRA_FAIL;
562     }
563     if (*num_entries < 1)
564     {
565         *num_entries = 0;
566         return ZEBRA_OK;
567     }
568     nmem = nmem_create();
569     kc = zebra_key_control_create(zh);
570
571     res = rpn_scan_norm(zh, stream, nmem, kc, zapt, position, num_entries,
572                         list, is_partial, limit_set,
573                         index_type, ord_no, ords);
574     nmem_destroy(nmem);
575     (*kc->dec)(kc);
576     return res;
577 }
578
579 /*
580  * Local variables:
581  * c-basic-offset: 4
582  * c-file-style: "Stroustrup"
583  * indent-tabs-mode: nil
584  * End:
585  * vim: shiftwidth=4 tabstop=8 expandtab
586  */
587