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