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