Re-estabslished rank-1. Gets same order of results, but slightly different
[idzebra-moved-to-github.git] / rset / rsmultiandor.c
1 /* $Id: rsmultiandor.c,v 1.8 2004-10-26 15:32:11 heikki Exp $
2    Copyright (C) 1995,1996,1997,1998,1999,2000,2001,2002
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 Zebra; see the file LICENSE.zebra.  If not, write to the
19 Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
20 02111-1307, USA.
21 */
22
23
24 /*
25  * This module implements the rsmultior and rsmultiand result sets
26  *
27  * rsmultior is based on a heap, from which we find the next hit.
28  *
29  * rsmultiand is based on a simple array of rsets, and a linear
30  * search to find the record that exists in all of those rsets.
31  * To speed things up, the array is sorted so that the smallest
32  * rsets come first, they are most likely to have the hits furthest
33  * away, and thus forwarding to them makes the most sense.
34  */
35
36
37 #include <assert.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <string.h>
41
42 #include <zebrautl.h>
43 #include <isamc.h>
44 #include <rset.h>
45
46 static RSFD r_open_and (RSET ct, int flag);
47 static RSFD r_open_or (RSET ct, int flag);
48 static void r_close (RSFD rfd);
49 static void r_delete (RSET ct);
50 static int r_read_and (RSFD rfd, void *buf, TERMID *term);
51 static int r_read_or (RSFD rfd, void *buf, TERMID *term);
52 static int r_write (RSFD rfd, const void *buf);
53 static int r_forward_and(RSFD rfd, void *buf, TERMID *term,
54                      const void *untilbuf);
55 static int r_forward_or(RSFD rfd, void *buf, TERMID *term,
56                      const void *untilbuf);
57 static void r_pos (RSFD rfd, double *current, double *total);
58 static void r_get_terms(RSET ct, TERMID *terms, int maxterms, int *curterm);
59
60 static const struct rset_control control_or = 
61 {
62     "multi-or",
63     r_delete,
64     r_get_terms,
65     r_open_or,
66     r_close,
67     r_forward_or,
68     r_pos,
69     r_read_or,
70     r_write,
71 };
72 static const struct rset_control control_and = 
73 {
74     "multi-and",
75     r_delete,
76     r_get_terms,
77     r_open_and,
78     r_close,
79     r_forward_and,
80     r_pos,
81     r_read_and,
82     r_write,
83 };
84
85 const struct rset_control *rset_kind_multior = &control_or;
86 const struct rset_control *rset_kind_multiand = &control_and;
87
88 /* The heap structure: 
89  * The rset contains a list or rsets we are ORing together 
90  * The rfd contains a heap of heap-items, which contain
91  * a rfd opened to those rsets, and a buffer for one key.
92  * They also contain a ptr to the rset list in the rset 
93  * itself, for practical reasons. 
94  */
95
96 struct heap_item {
97     RSFD fd;
98     void *buf;
99     RSET rset;
100     TERMID term;
101 };
102
103 struct heap {
104     int heapnum;
105     int heapmax;
106     const struct key_control *kctrl;
107     struct heap_item **heap; /* ptrs to the rfd */
108 };
109 typedef struct heap *HEAP;
110
111
112 struct rset_multiandor_info {
113     int     no_rsets;
114     RSET    *rsets;
115 };
116
117
118 struct rset_multiandor_rfd {
119     int flag;
120     struct heap_item *items; /* we alloc and free them here */
121     HEAP h; /* and move around here */
122     zint hits; /* returned so far */
123     int eof; /* seen the end of it */
124     int tailcount; /* how many items are tailing */
125     char *tailbits;
126 };
127
128 /* Heap functions ***********************/
129
130 #if 0
131 static void heap_dump_item( HEAP h, int i, int level) {
132     double cur,tot;
133     if (i>h->heapnum)
134         return;
135     (void)rset_pos(h->heap[i]->rset,h->heap[i]->fd, &cur, &tot);
136     logf(LOG_LOG," %d %*s i=%p buf=%p %0.1f/%0.1f",i, level, "",  
137                     &(h->heap[i]), h->heap[i]->buf, cur,tot );
138     heap_dump_item(h, 2*i, level+1);
139     heap_dump_item(h, 2*i+1, level+1);
140 }
141 static void heap_dump( HEAP h,char *msg) {
142     logf(LOG_LOG, "heap dump: %s num=%d max=%d",msg, h->heapnum, h->heapmax);
143     heap_dump_item(h,1,1);
144 }
145 #endif
146
147 static void heap_swap (HEAP h, int x, int y)
148 {
149     struct heap_item *swap;
150     swap = h->heap[x];
151     h->heap[x]=h->heap[y];
152     h->heap[y]=swap;
153 }
154
155 static int heap_cmp(HEAP h, int x, int y)
156 {
157     return (*h->kctrl->cmp)(h->heap[x]->buf,h->heap[y]->buf);
158 }
159
160 static int heap_empty(HEAP h)
161 {
162     return ( 0==h->heapnum );
163 }
164
165 static void heap_delete (HEAP h)
166 { /* deletes the first item in the heap, and balances the rest */
167     int cur = 1, child = 2;
168     h->heap[1]=0; /* been deleted */
169     heap_swap (h, 1, h->heapnum--);
170     while (child <= h->heapnum) {
171         if (child < h->heapnum && heap_cmp(h,child,1+child)>0 )
172             child++;
173         if (heap_cmp(h,cur,child) > 0)
174         {
175             heap_swap (h, cur, child);
176             cur = child;
177             child = 2*cur;
178         }
179         else
180             break;
181     }
182 }
183
184 static void heap_balance (HEAP h)
185 { /* The heap root element has changed value (to bigger) */
186   /* swap downwards until the heap is ordered again */
187     int cur = 1, child = 2;
188     while (child <= h->heapnum) {
189         if (child < h->heapnum && heap_cmp(h,child,1+child)>0 )
190             child++;
191         if (heap_cmp(h,cur,child) > 0)
192         {
193             heap_swap (h, cur, child);
194             cur = child;
195             child = 2*cur;
196         }
197         else
198             break;
199     }
200 }
201
202
203 static void heap_insert (HEAP h, struct heap_item *hi)
204 {
205     int cur, parent;
206
207     cur = ++(h->heapnum);
208     assert(cur <= h->heapmax);
209     h->heap[cur]=hi;
210     parent = cur/2;
211     while (parent && (heap_cmp(h,parent,cur) > 0))
212     {
213         assert(parent>0);
214         heap_swap (h, cur, parent);
215         cur = parent;
216         parent = cur/2;
217     }
218 }
219
220
221 static
222 HEAP heap_create (NMEM nmem, int size, const struct key_control *kctrl)
223 {
224     HEAP h = (HEAP) nmem_malloc (nmem, sizeof(*h));
225
226     ++size; /* heap array starts at 1 */
227     h->heapnum = 0;
228     h->heapmax = size;
229     h->kctrl=kctrl;
230     h->heap = (struct heap_item**) nmem_malloc(nmem,size*sizeof(*h->heap));
231     h->heap[0]=0; /* not used */
232     return h;
233 }
234
235 static void heap_clear( HEAP h)
236 {
237     assert(h);
238     h->heapnum=0;
239 }
240
241 static void heap_destroy (HEAP h)
242 {
243     /* nothing to delete, all is nmem'd, and will go away in due time */
244 }
245
246 int compare_ands(const void *x, const void *y)
247 { /* used in qsort to get the multi-and args in optimal order */
248   /* that is, those with fewest occurrences first */
249     const struct heap_item *hx=x;
250     const struct heap_item *hy=y;
251     double cur, totx, toty;
252     rset_pos(hx->fd, &cur, &totx);
253     rset_pos(hy->fd, &cur, &toty);
254     if ( totx > toty +0.5 ) return 1;
255     if ( totx < toty -0.5 ) return -1;
256     return 0;  /* return totx - toty, except for overflows and rounding */
257 }
258
259 /* Creating and deleting rsets ***********************/
260
261 static RSET rsmulti_andor_create( NMEM nmem, const struct key_control *kcontrol, 
262                            int scope, int no_rsets, RSET* rsets, 
263                            const struct rset_control *ctrl)
264 {
265     RSET rnew=rset_create_base(ctrl, nmem,kcontrol, scope,0);
266     struct rset_multiandor_info *info;
267     info = (struct rset_multiandor_info *) nmem_malloc(rnew->nmem,sizeof(*info));
268     info->no_rsets=no_rsets;
269     info->rsets=(RSET*)nmem_malloc(rnew->nmem, no_rsets*sizeof(*rsets));
270     memcpy(info->rsets,rsets,no_rsets*sizeof(*rsets));
271     rnew->priv=info;
272     return rnew;
273 }
274
275 RSET rsmultior_create( NMEM nmem, const struct key_control *kcontrol, int scope,
276             int no_rsets, RSET* rsets)
277 {
278     return rsmulti_andor_create(nmem, kcontrol, scope, 
279                                 no_rsets, rsets, &control_or);
280 }
281
282 RSET rsmultiand_create( NMEM nmem, const struct key_control *kcontrol, int scope,
283             int no_rsets, RSET* rsets)
284 {
285     return rsmulti_andor_create(nmem, kcontrol, scope, 
286                                 no_rsets, rsets, &control_and);
287 }
288
289 static void r_delete (RSET ct)
290 {
291     struct rset_multiandor_info *info = (struct rset_multiandor_info *) ct->priv;
292     int i;
293     for(i=0;i<info->no_rsets;i++)
294         rset_delete(info->rsets[i]);
295 }
296
297
298 /* Opening and closing fd's on them *********************/
299
300 static RSFD r_open_andor (RSET ct, int flag, int is_and)
301 {
302     RSFD rfd;
303     struct rset_multiandor_rfd *p;
304     struct rset_multiandor_info *info = (struct rset_multiandor_info *) ct->priv;
305     const struct key_control *kctrl = ct->keycontrol;
306     int i;
307
308     if (flag & RSETF_WRITE)
309     {
310         logf (LOG_FATAL, "multiandor set type is read-only");
311         return NULL;
312     }
313     rfd=rfd_create_base(ct);
314     if (rfd->priv) {
315         p=(struct rset_multiandor_rfd *)rfd->priv;
316         if (!is_and)
317             heap_clear(p->h);
318         assert(p->items);
319         /* all other pointers shouls already be allocated, in right sizes! */
320     }
321     else {
322         p = (struct rset_multiandor_rfd *) nmem_malloc (ct->nmem,sizeof(*p));
323         rfd->priv=p;
324         p->h=0;
325         p->tailbits=0;
326         if (is_and)
327             p->tailbits=nmem_malloc(ct->nmem, info->no_rsets*sizeof(char) );
328         else 
329             p->h = heap_create( ct->nmem, info->no_rsets, kctrl);
330         p->items=(struct heap_item *) nmem_malloc(ct->nmem,
331                               info->no_rsets*sizeof(*p->items));
332         for (i=0; i<info->no_rsets; i++){
333             p->items[i].rset=info->rsets[i];
334             p->items[i].buf=nmem_malloc(ct->nmem,kctrl->key_size);
335         }
336     }
337     p->flag = flag;
338     p->hits=0;
339     p->eof=0;
340     p->tailcount=0;
341     if (is_and)
342     { /* read the array and sort it */
343         for (i=0; i<info->no_rsets; i++){
344             p->items[i].fd=rset_open(info->rsets[i],RSETF_READ);
345             if (!rset_read(p->items[i].fd, p->items[i].buf, &p->items[i].term))
346                 p->eof=1;
347             p->tailbits[i]=0;
348         }
349         qsort(p->items, info->no_rsets, sizeof(p->items[0]), compare_ands);
350     } else
351     { /* fill the heap for ORing */
352         for (i=0; i<info->no_rsets; i++){
353             p->items[i].fd=rset_open(info->rsets[i],RSETF_READ);
354             if ( rset_read(p->items[i].fd, p->items[i].buf, &p->items[i].term))
355                 heap_insert(p->h, &(p->items[i]));
356         }
357     }
358     return rfd;
359 }
360
361 static RSFD r_open_or (RSET ct, int flag)
362 {
363     return r_open_andor(ct, flag, 0);
364 }
365
366 static RSFD r_open_and (RSET ct, int flag)
367 {
368     return r_open_andor(ct, flag, 1);
369 }
370
371
372 static void r_close (RSFD rfd)
373 {
374     struct rset_multiandor_info *info=
375         (struct rset_multiandor_info *)(rfd->rset->priv);
376     struct rset_multiandor_rfd *p=(struct rset_multiandor_rfd *)(rfd->priv);
377     int i;
378
379     if (p->h)
380         heap_destroy (p->h);
381     for (i = 0; i<info->no_rsets; i++) 
382         if (p->items[i].fd)
383             rset_close(p->items[i].fd);
384     rfd_delete_base(rfd);
385 }
386
387
388
389 static int r_forward_or(RSFD rfd, void *buf, 
390                         TERMID *term,const void *untilbuf)
391 { /* while heap head behind untilbuf, forward it and rebalance heap */
392     struct rset_multiandor_rfd *p=rfd->priv;
393     const struct key_control *kctrl=rfd->rset->keycontrol;
394     if (heap_empty(p->h))
395         return 0;
396     while ( (*kctrl->cmp)(p->h->heap[1]->buf,untilbuf) < -rfd->rset->scope )
397     {
398         if (rset_forward(p->h->heap[1]->fd,p->h->heap[1]->buf,
399                          &p->h->heap[1]->term, untilbuf))
400             heap_balance(p->h);
401         else 
402         {
403             heap_delete(p->h);
404             if (heap_empty(p->h))
405                 return 0;
406         }
407
408     }
409     return r_read_or(rfd,buf,term);
410 }
411
412
413 static int r_read_or (RSFD rfd, void *buf, TERMID *term)
414 {
415     struct rset_multiandor_rfd *mrfd=rfd->priv;
416     const struct key_control *kctrl=rfd->rset->keycontrol;
417     struct heap_item *it;
418     int rdres;
419     if (heap_empty(mrfd->h))
420         return 0;
421     it = mrfd->h->heap[1];
422     memcpy(buf,it->buf, kctrl->key_size); 
423     if (term)
424         *term=it->term;
425     (mrfd->hits)++;
426     rdres=rset_read(it->fd, it->buf, &it->term);
427     if ( rdres )
428         heap_balance(mrfd->h);
429     else
430         heap_delete(mrfd->h);
431     return 1;
432
433 }
434
435 static int r_read_and (RSFD rfd, void *buf, TERMID *term)
436 { /* Has to return all hits where each item points to the */
437   /* same sysno (scope), in order. Keep an extra key (hitkey) */
438   /* as long as all records do not point to hitkey, forward */
439   /* them, and update hitkey to be the highest seen so far. */
440   /* (if any item eof's, mark eof, and return 0 thereafter) */
441   /* Once a hit has been found, scan all items for the smallest */
442   /* value. Mark all as being in the tail. Read next from that */
443   /* item, and if not in the same record, clear its tail bit */
444     struct rset_multiandor_rfd *p=rfd->priv;
445     const struct key_control *kctrl=rfd->rset->keycontrol;
446     struct rset_multiandor_info *info=rfd->rset->priv;
447     int i, mintail;
448     int cmp;
449
450     while (1) {
451         if (p->tailcount) 
452         { /* we are tailing, find lowest tail and return it */
453             mintail=0;
454             while ((mintail<info->no_rsets) && !p->tailbits[mintail])
455                 mintail++; /* first tail */
456             for (i=mintail+1;i<info->no_rsets;i++)
457             {
458                 if (p->tailbits[i])
459                 {
460                     cmp=(*kctrl->cmp)(p->items[i].buf,p->items[mintail].buf);
461                     if (cmp<0) 
462                         mintail=i;
463                 }
464             }
465             /* return the lowest tail */
466             memcpy(buf, p->items[mintail].buf, kctrl->key_size); 
467             if (term)
468                 *term=p->items[mintail].term;
469             if (!rset_read(p->items[mintail].fd, p->items[mintail].buf,
470                            &p->items[mintail].term))
471             {
472                 p->eof=1; /* game over, once tails have been returned */
473                 p->tailbits[mintail]=0; 
474                 (p->tailcount)--;
475                 return 1;
476             }
477             /* still a tail? */
478             cmp=(*kctrl->cmp)(p->items[mintail].buf,buf);
479             if (cmp >= rfd->rset->scope){
480                 p->tailbits[mintail]=0;
481                 (p->tailcount)--;
482             }
483             return 1;
484         } 
485         /* not tailing, forward until all reocrds match, and set up */
486         /* as tails. the earlier 'if' will then return the hits */
487         if (p->eof)
488             return 0; /* nothing more to see */
489         i=1; /* assume items[0] is highest up */
490         while (i<info->no_rsets) {
491             cmp=(*kctrl->cmp)(p->items[0].buf,p->items[i].buf);
492             if (cmp<=-rfd->rset->scope) { /* [0] was behind, forward it */
493                 if (!rset_forward(p->items[0].fd, p->items[0].buf, 
494                                   &p->items[0].term, p->items[i].buf))
495                 {
496                     p->eof=1; /* game over */
497                     return 0;
498                 }
499                 i=0; /* start frowarding from scratch */
500             } else if (cmp>=rfd->rset->scope)
501             { /* [0] was ahead, forward i */
502                 if (!rset_forward(p->items[i].fd, p->items[i].buf, 
503                                   &p->items[i].term, p->items[0].buf))
504                 {
505                     p->eof=1; /* game over */
506                     return 0;
507                 }
508             } else
509                 i++;
510         } /* while i */
511         /* if we get this far, all rsets are now within +- scope of [0] */
512         /* ergo, we have a hit. Mark them all as tailing, and let the */
513         /* upper 'if' return the hits in right order */
514         for (i=0; i<info->no_rsets;i++)
515             p->tailbits[i]=1;
516         p->tailcount=info->no_rsets;
517     } /* while 1 */
518 }
519
520
521 static int r_forward_and(RSFD rfd, void *buf, TERMID *term, 
522                          const void *untilbuf)
523
524     struct rset_multiandor_rfd *p=rfd->priv;
525     const struct key_control *kctrl=rfd->rset->keycontrol;
526     struct rset_multiandor_info *info=rfd->rset->priv;
527     int i;
528     int cmp;
529     int killtail=0;
530
531     for (i=0; i<info->no_rsets;i++)
532     {
533         cmp=(*kctrl->cmp)(p->items[i].buf,untilbuf);
534         if ( cmp <= -rfd->rset->scope )
535         {
536             killtail=1; /* we are moving to a different hit */
537             if (!rset_forward(p->items[i].fd, p->items[i].buf, 
538                               &p->items[i].term, untilbuf))
539             {
540                 p->eof=1; /* game over */
541                 p->tailcount=0;
542                 return 0;
543             }
544         }
545     }
546     if (killtail) 
547     {
548         for (i=0; i<info->no_rsets;i++)
549             p->tailbits[i]=0;
550         p->tailcount=0;
551     }
552     return r_read_and(rfd,buf,term);
553 }
554
555 static void r_pos (RSFD rfd, double *current, double *total)
556 {
557     struct rset_multiandor_info *info=
558              (struct rset_multiandor_info *)(rfd->rset->priv);
559     struct rset_multiandor_rfd *mrfd=(struct rset_multiandor_rfd *)(rfd->priv);
560     double cur, tot;
561     double scur=0.0, stot=0.0;
562     int i;
563     for (i=0; i<info->no_rsets; i++){
564         rset_pos(mrfd->items[i].fd, &cur, &tot);
565         /*logf(LOG_LOG, "r_pos: %d %0.1f %0.1f", i, cur,tot); */
566         scur += cur;
567         stot += tot;
568     }
569     if (stot <1.0) { /* nothing there */
570         *current=0;
571         *total=0;
572         /* logf(LOG_LOG, "r_pos: NULL  %0.1f %0.1f",  *current, *total);*/
573         return;
574     }
575     *current=mrfd->hits;
576     *total=*current*stot/scur;
577     /*logf(LOG_LOG, "r_pos: =  %0.1f %0.1f",  *current, *total);*/
578 }
579
580
581
582 static int r_write (RSFD rfd, const void *buf)
583 {
584     logf (LOG_FATAL, "multior set type is read-only");
585     return -1;
586 }
587
588 static void r_get_terms(RSET ct, TERMID *terms, int maxterms, int *curterm)
589     /* Special case: Some multi-ors have all terms pointing to the same */
590     /* term. We do not want to duplicate those. Other multiors (and ands) */
591     /* have different terms under them. Those we want. */
592 {
593     struct rset_multiandor_info *info = 
594         (struct rset_multiandor_info *) ct->priv;
595     int firstterm= *curterm;
596     int i;
597     for (i=0;i<info->no_rsets;i++)
598     {
599         rset_getterms(info->rsets[i], terms, maxterms, curterm);
600         if ( ( (*curterm) > firstterm+1 ) &&
601              ( (*curterm) <= maxterms ) &&
602              ( terms[(*curterm)-1] == terms[firstterm] ) )
603             (*curterm)--; /* forget the term, seen that before */
604     }
605 }
606
607