3a760f419d615d0590f7f80077cebabd84e25039
[yaz-moved-to-github.git] / src / solr.c
1 /* This file is part of the YAZ toolkit.
2  * Copyright (C) Index Data
3  * See the file LICENSE for details.
4  */
5 /**
6  * \file solr.c
7  * \brief Implements Solr decoding/encoding
8  */
9 #if HAVE_CONFIG_H
10 #include <config.h>
11 #endif
12
13 #include <stdlib.h>
14 #include <assert.h>
15 #include <yaz/srw.h>
16 #include <yaz/matchstr.h>
17 #include <yaz/yaz-iconv.h>
18 #include <yaz/log.h>
19 #include <yaz/facet.h>
20 #include <yaz/wrbuf.h>
21 #include <yaz/proto.h>
22
23 #include "sru-p.h"
24
25 #if YAZ_HAVE_XML2
26 #include <libxml/parser.h>
27 #include <libxml/tree.h>
28
29 static void extract_text_node(xmlNodePtr node, WRBUF wrbuf) {
30     xmlNodePtr child;
31     for (child = node->children; child ; child = child->next)
32     {
33         if (child->type == XML_TEXT_NODE)
34             wrbuf_puts(wrbuf, (const char *) child->content);
35     }
36 }
37
38 static int match_xml_node_attribute(
39     xmlNodePtr ptr,
40     const char *node_name, const char *attribute_name, const char *value)
41 {
42     const char *attribute_value;
43     // check if the node name matches
44     if (strcmp((const char*) ptr->name, node_name))
45         return 0;
46     if (attribute_name)
47     {
48         attribute_value = yaz_element_attribute_value_get(ptr, node_name,
49                                                           attribute_name);
50         if (attribute_value && !strcmp(attribute_value, value))
51             return 1;
52     }
53     else /* No attribute to check */
54         return 1;
55     return 0;
56 }
57
58 static void yaz_solr_decode_result_docs(ODR o, xmlNodePtr ptr,
59                                         Odr_int start,
60                                         Z_SRW_searchRetrieveResponse *sr)
61 {
62     xmlNodePtr node;
63     int offset = 0;
64     int i = 0;
65
66     sr->num_records = 0;
67     for (node = ptr->children; node; node = node->next)
68         if (node->type == XML_ELEMENT_NODE)
69             sr->num_records++;
70
71     if (sr->num_records)
72         sr->records = odr_malloc(o, sizeof(*sr->records) * sr->num_records);
73
74     for (node = ptr->children; node; node = node->next)
75     {
76         if (node->type == XML_ELEMENT_NODE)
77         {
78             Z_SRW_record *record = sr->records + i;
79             xmlBufferPtr buf = xmlBufferCreate();
80             xmlNode *tmp = xmlCopyNode(node, 1);
81
82             xmlNodeDump(buf, tmp->doc, tmp, 0, 0);
83
84             xmlFreeNode(tmp);
85
86             record->recordSchema = 0;
87             record->recordPacking = Z_SRW_recordPacking_XML;
88             record->recordData_len = buf->use;
89             record->recordData_buf =
90                 odr_strdupn(o, (const char *) buf->content, buf->use);
91             record->recordPosition = odr_intdup(o, start + offset + 1);
92
93             xmlBufferFree(buf);
94
95             offset++;
96             i++;
97         }
98     }
99 }
100
101 static int yaz_solr_decode_result(ODR o, xmlNodePtr ptr,
102                                   Z_SRW_searchRetrieveResponse *sr)
103 {
104     Odr_int start = 0;
105     struct _xmlAttr *attr;
106     for (attr = ptr->properties; attr; attr = attr->next)
107         if (attr->children && attr->children->type == XML_TEXT_NODE)
108         {
109             if (!strcmp((const char *) attr->name, "numFound"))
110             {
111                 sr->numberOfRecords = odr_intdup(o, odr_atoi(
112                         (const char *) attr->children->content));
113             }
114             else if (!strcmp((const char *) attr->name, "start"))
115             {
116                 start = odr_atoi((const char *) attr->children->content);
117             }
118         }
119     if (sr->numberOfRecords && *sr->numberOfRecords > 0)
120         yaz_solr_decode_result_docs(o, ptr, start, sr);
121     if (sr->numberOfRecords)
122         return 0;
123     return -1;
124 }
125
126 static const char *get_facet_term_count(xmlNodePtr node, Odr_int *freq)
127 {
128     const char *term = yaz_element_attribute_value_get(node, "int", "name");
129     xmlNodePtr child;
130     WRBUF wrbuf = wrbuf_alloc();
131     if (!term)
132         return term;
133
134     for (child = node->children; child ; child = child->next)
135     {
136         if (child->type == XML_TEXT_NODE)
137             wrbuf_puts(wrbuf, (const char *) child->content);
138     }
139     *freq = odr_atoi(wrbuf_cstr(wrbuf));
140     wrbuf_destroy(wrbuf);
141     return term;
142 }
143
144 Z_FacetField *yaz_solr_decode_facet_field(ODR o, xmlNodePtr ptr,
145                                           Z_SRW_searchRetrieveResponse *sr)
146
147 {
148     Z_AttributeList *list;
149     Z_FacetField *facet_field;
150     int num_terms = 0;
151     int index = 0;
152     xmlNodePtr node;
153     // USE attribute
154     const char* name = yaz_element_attribute_value_get(ptr, "lst", "name");
155     list = zget_AttributeList_use_string(o, name);
156     for (node = ptr->children; node; node = node->next)
157         num_terms++;
158     facet_field = facet_field_create(o, list, num_terms);
159     index = 0;
160     for (node = ptr->children; node; node = node->next)
161     {
162         Odr_int count = 0;
163         const char *term = get_facet_term_count(node, &count);
164         facet_field_term_set(o, facet_field,
165                              facet_term_create_cstr(o, term, count), index);
166         index++;
167     }
168     return facet_field;
169 }
170
171 static int yaz_solr_decode_facet_counts(ODR o, xmlNodePtr root,
172                                         Z_SRW_searchRetrieveResponse *sr)
173 {
174     xmlNodePtr ptr;
175     for (ptr = root->children; ptr; ptr = ptr->next)
176     {
177         if (match_xml_node_attribute(ptr, "lst", "name", "facet_fields"))
178         {
179             xmlNodePtr node;
180             Z_FacetList *facet_list;
181             int num_facets = 0;
182             for (node = ptr->children; node; node= node->next)
183             {
184                 num_facets++;
185             }
186             facet_list = facet_list_create(o, num_facets);
187             num_facets = 0;
188             for (node = ptr->children; node; node= node->next)
189             {
190                 facet_list_field_set(o, facet_list,
191                                      yaz_solr_decode_facet_field(o, node, sr),
192                                      num_facets);
193                 num_facets++;
194             }
195             sr->facetList = facet_list;
196             break;
197         }
198     }
199     return 0;
200 }
201
202 static void yaz_solr_decode_suggestion_values(xmlNodePtr listPptr, WRBUF wrbuf)
203 {
204     xmlNodePtr node;
205     for (node = listPptr; node; node= node->next) {
206         if (!strcmp((char*) node->name, "lst")) {
207             xmlNodePtr child;
208             for (child = node->children; child; child= child->next) {
209                 if (match_xml_node_attribute(child, "str", "name", "word")) {
210                     wrbuf_puts(wrbuf, "<suggestion>");
211                     extract_text_node(child, wrbuf);
212                     wrbuf_puts(wrbuf, "</suggestion>\n");
213                 }
214             }
215         }
216     }
217 }
218
219 static void yaz_solr_decode_suggestion_lst(xmlNodePtr lstPtr, WRBUF wrbuf)
220 {
221     xmlNodePtr node;
222     for (node = lstPtr; node; node= node->next) {
223         if (match_xml_node_attribute(node, "arr", "name", "suggestion")) {
224             yaz_solr_decode_suggestion_values(node->children, wrbuf);
225         }
226     }
227 }
228
229 static void yaz_solr_decode_misspelled(xmlNodePtr lstPtr, WRBUF wrbuf)
230 {
231     xmlNodePtr node;
232     for (node = lstPtr; node; node= node->next)
233     {
234         if (!strcmp((const char*) node->name, "lst")) {
235             const char *misspelled = yaz_element_attribute_value_get(node, "lst", "name");
236             if (misspelled) {
237                 wrbuf_printf(wrbuf, "<misspelled term=\"%s\">\n", misspelled);
238                 yaz_solr_decode_suggestion_lst(node->children, wrbuf);
239                 wrbuf_puts(wrbuf, "</misspelled>\n");
240             }
241         }
242     }
243 }
244
245 static int yaz_solr_decode_spellcheck(ODR o, xmlNodePtr spellcheckPtr, Z_SRW_searchRetrieveResponse *sr)
246 {
247     xmlNodePtr ptr;
248     WRBUF wrbuf = wrbuf_alloc();
249     wrbuf_puts(wrbuf, "");
250     for (ptr = spellcheckPtr->children; ptr; ptr = ptr->next)
251     {
252         if (match_xml_node_attribute(ptr, "lst", "name", "suggestions"))
253         {
254             yaz_solr_decode_misspelled(ptr->children, wrbuf);
255         }
256     }
257     sr->suggestions = odr_strdup(o, wrbuf_cstr(wrbuf));
258     return 0;
259 }
260
261 static int yaz_solr_decode_scan_result(ODR o, xmlNodePtr ptr,
262                                        Z_SRW_scanResponse *scr)
263 {
264     xmlNodePtr node;
265     char *pos;
266     int i = 0;
267
268     /* find the actual list */
269     for (node = ptr->children; node; node = node->next)
270         if (node->type == XML_ELEMENT_NODE) {
271             ptr = node;
272             break;
273         }
274
275     scr->num_terms = 0;
276     for (node = ptr->children; node; node = node->next)
277         if (node->type == XML_ELEMENT_NODE && !strcmp((const char *) node->name, "int"))
278             scr->num_terms++;
279
280     if (scr->num_terms)
281         scr->terms = odr_malloc(o, sizeof(*scr->terms) * scr->num_terms);
282
283     for (node = ptr->children; node; node = node->next)
284     {
285         if (node->type == XML_ELEMENT_NODE && !strcmp((const char *) node->name, "int"))
286         {
287             Z_SRW_scanTerm *term = scr->terms + i;
288
289             Odr_int count = 0;
290             const char *val = get_facet_term_count(node, &count);
291
292             term->numberOfRecords = odr_intdup(o, count);
293
294             /* if val contains a ^ then it is probably term<^>display term so separate them. This is due to
295              * SOLR not being able to encode them into 2 separate attributes.
296              */
297             pos = strchr(val, '^');
298             if (pos != NULL) {
299                 term->displayTerm = odr_strdup(o, pos + 1);
300                 *pos = '\0';
301                 term->value = odr_strdup(o, val);
302                 *pos = '^';
303             } else {
304                 term->value = odr_strdup(o, val);
305                 term->displayTerm = NULL;
306             }
307             term->whereInList = NULL;
308
309             i++;
310         }
311     }
312
313     if (scr->num_terms)
314         return 0;
315     return -1;
316 }
317 #endif
318
319 int yaz_solr_decode_response(ODR o, Z_HTTP_Response *hres, Z_SRW_PDU **pdup)
320 {
321 #if YAZ_HAVE_XML2
322     const char *content_buf = hres->content_buf;
323     int content_len = hres->content_len;
324     xmlDocPtr doc = xmlParseMemory(content_buf, content_len);
325     int ret = 0;
326     xmlNodePtr ptr = 0;
327     Z_SRW_PDU *pdu;
328     Z_SRW_searchRetrieveResponse *sr = NULL;
329     Z_SRW_scanResponse *scr = NULL;
330
331     if (!doc)
332     {
333         ret = -1;
334     }
335     if (doc)
336     {
337         xmlNodePtr root = xmlDocGetRootElement(doc);
338         if (!root)
339         {
340             ret = -1;
341         }
342         else if (strcmp((const char *) root->name, "response"))
343         {
344             ret = -1;
345         }
346         else
347         {
348             /** look for result (required) and facets node (optional) */
349             int rc_result = -1;
350             int rc_facets = 0;
351             for (ptr = root->children; ptr; ptr = ptr->next)
352             {
353                 if (ptr->type == XML_ELEMENT_NODE &&
354                     !strcmp((const char *) ptr->name, "result")) {
355                         pdu = yaz_srw_get(o, Z_SRW_searchRetrieve_response);
356                         sr = pdu->u.response;
357                         rc_result = yaz_solr_decode_result(o, ptr, sr);
358                 }
359                 if (ptr->type == XML_ELEMENT_NODE &&
360                     match_xml_node_attribute(ptr, "lst", "name", "terms")) {
361                         pdu = yaz_srw_get(o, Z_SRW_scan_response);
362                         scr = pdu->u.scan_response;
363                         rc_result = yaz_solr_decode_scan_result(o, ptr, scr);
364                 }
365                 /* TODO The check on hits is a work-around to avoid garbled facets on zero results from the SOLR server.
366                  * The work-around works because the results is before the facets in the xml. */
367                 if (sr) {
368                     if (rc_result == 0 &&  *sr->numberOfRecords > 0 &&
369                         match_xml_node_attribute(ptr, "lst", "name", "facet_counts"))
370                             rc_facets =  yaz_solr_decode_facet_counts(o, ptr, sr);
371                     if (rc_result == 0 &&  *sr->numberOfRecords == 0 &&
372                         match_xml_node_attribute(ptr, "lst", "name", "spellcheck"))
373                             rc_facets =  yaz_solr_decode_spellcheck(o, ptr, sr);
374                 }
375
376             }
377             ret = rc_result + rc_facets;
378         }
379     }
380     if (doc)
381         xmlFreeDoc(doc);
382     if (ret == 0)
383         *pdup = pdu;
384     return ret;
385 #else
386     return -1;
387 #endif
388 }
389
390 static int yaz_solr_encode_facet_field(
391     ODR encode, char **name, char **value, int *i,
392     Z_FacetField *facet_field)
393 {
394     Z_AttributeList *attribute_list = facet_field->attributes;
395     struct yaz_facet_attr attr_values;
396     yaz_facet_attr_init(&attr_values);
397     yaz_facet_attr_get_z_attributes(attribute_list, &attr_values);
398
399     if (attr_values.errcode)
400         return -1;
401     if (attr_values.useattr)
402     {
403         WRBUF wrbuf = wrbuf_alloc();
404         yaz_add_name_value_str(encode, name, value, i,
405                                "facet.field",
406                                odr_strdup(encode, attr_values.useattr));
407
408         if (attr_values.limit > 0)
409         {
410             Odr_int v = attr_values.limit;
411             wrbuf_rewind(wrbuf);
412             wrbuf_printf(wrbuf, "f.%s.facet.limit", attr_values.useattr);
413             yaz_add_name_value_int(encode, name, value, i,
414                                    odr_strdup(encode, wrbuf_cstr(wrbuf)),
415                                    &v);
416         }
417         if (attr_values.start > 1)
418         {
419             Odr_int v = attr_values.start - 1;
420             wrbuf_rewind(wrbuf);
421             wrbuf_printf(wrbuf, "f.%s.facet.offset", attr_values.useattr);
422             yaz_add_name_value_int(encode, name, value, i,
423                                    odr_strdup(encode, wrbuf_cstr(wrbuf)),
424                                    &v);
425         }
426         if (attr_values.sortorder == 1)
427         {
428             wrbuf_rewind(wrbuf);
429             wrbuf_printf(wrbuf, "f.%s.facet.sort", attr_values.useattr);
430             yaz_add_name_value_str(encode, name, value, i,
431                                    odr_strdup(encode, wrbuf_cstr(wrbuf)),
432                                    "index");
433         }
434         wrbuf_destroy(wrbuf);
435     }
436     else
437     {
438         if (attr_values.limit > 0)
439         {
440             Odr_int v = attr_values.limit;
441             yaz_add_name_value_int(encode, name, value, i, "facet.limit", &v);
442         }
443         if (attr_values.start > 1)
444         {
445             Odr_int v = attr_values.start - 1;
446             yaz_add_name_value_int(encode, name, value, i, "facet.offset", &v);
447         }
448         if (attr_values.sortorder == 1)
449         {
450             yaz_add_name_value_str(encode, name, value, i, "facet.sort",
451                                    "index");
452         }
453     }
454     return 0;
455 }
456
457 static int yaz_solr_encode_facet_list(
458     ODR encode, char **name, char **value,
459     int *i, Z_FacetList *facet_list)
460 {
461     int index;
462     for (index = 0; index < facet_list->num; index++)
463     {
464         int r = yaz_solr_encode_facet_field(encode, name, value, i,
465                                             facet_list->elements[index]);
466         if (r)
467             return -1;
468
469     }
470     return 0;
471 }
472
473 int yaz_solr_encode_request(Z_HTTP_Request *hreq, Z_SRW_PDU *srw_pdu,
474                             ODR encode, const char *charset)
475 {
476     const char *solr_op = 0;
477     char **name, **value;
478     char *uri_args;
479     char *path;
480     char *q;
481     char *pos;
482     char *cp;
483     const char *path_args = 0;
484     int i = 0;
485     int no_parms = 20; /* safe upper limit of args without extra_args */
486     Z_SRW_extra_arg *ea;
487
488     for (ea = srw_pdu->extra_args; ea; ea = ea->next)
489         no_parms++;
490     name = (char **) odr_malloc(encode, sizeof(*name) * no_parms);
491     value = (char **) odr_malloc(encode, sizeof(*value) * no_parms);
492
493     for (ea = srw_pdu->extra_args; ea; ea = ea->next)
494     {
495         name[i] = ea->name;
496         value[i] = ea->value;
497         i++;
498     }
499
500     z_HTTP_header_add_basic_auth(encode, &hreq->headers,
501                                  srw_pdu->username, srw_pdu->password);
502     if (srw_pdu->which == Z_SRW_searchRetrieve_request)
503     {
504         Z_SRW_searchRetrieveRequest *request = srw_pdu->u.request;
505         solr_op = "select";
506         if (!srw_pdu->u.request->query)
507             return -1;
508         yaz_add_name_value_str(encode, name, value, &i, "defType", "lucene");
509         yaz_add_name_value_str(encode, name, value, &i, "q", request->query);
510         if (srw_pdu->u.request->startRecord)
511         {
512             Odr_int start = *request->startRecord - 1;
513             yaz_add_name_value_int(encode, name, value, &i,
514                                    "start", &start);
515         }
516         yaz_add_name_value_int(encode, name, value, &i,
517                                "rows", request->maximumRecords);
518         yaz_add_name_value_str(encode, name, value, &i,
519                                "fl", request->recordSchema);
520
521         switch(srw_pdu->u.request->sort_type)
522         {
523         case Z_SRW_sort_type_none:
524             break;
525         case Z_SRW_sort_type_sort:
526             yaz_add_name_value_str(encode, name, value, &i, "sort",
527                                    srw_pdu->u.request->sort.sortKeys);
528             break;
529         }
530         if (request->facetList)
531         {
532             Z_FacetList *facet_list = request->facetList;
533             yaz_add_name_value_str(encode, name, value, &i, "facet", "true");
534             yaz_add_name_value_str(encode, name, value, &i, "facet.mincount", "1");
535             if (yaz_solr_encode_facet_list(encode, name, value, &i, facet_list))
536                 return -1;
537         }
538     }
539     else if (srw_pdu->which == Z_SRW_scan_request) {
540         Z_SRW_scanRequest *request = srw_pdu->u.scan_request;
541         solr_op = "terms";
542         if (!srw_pdu->u.scan_request->scanClause)
543             return -1;
544         if (!strcmp(srw_pdu->u.scan_request->queryType, "pqf"))
545         {
546             yaz_add_name_value_str(encode, name, value, &i,
547                                    "terms.fl", request->scanClause);
548             yaz_add_name_value_str(encode, name, value, &i,
549                                    "terms.lower", request->scanClause);
550         }
551         else if (!strcmp(srw_pdu->u.scan_request->queryType, "cql"))
552         {
553             q = request->scanClause;
554             pos = strchr(q, ':');
555             if (pos != NULL) {
556                 yaz_add_name_value_str(encode, name, value, &i,
557                                        "terms.lower", odr_strdup(encode, pos + 1));
558                 *pos = '\0';
559                 yaz_add_name_value_str(encode, name, value, &i,
560                                        "terms.fl", odr_strdup(encode, q));
561                 *pos = ':';
562             } else {
563                 yaz_add_name_value_str(encode, name, value, &i,
564                                        "terms.lower", odr_strdup(encode, q));
565             }
566         }
567         else
568             return -1;
569         yaz_add_name_value_str(encode, name, value, &i,
570                                "terms.sort", "index");
571         yaz_add_name_value_int(encode, name, value, &i,
572                                "terms.limit", request->maximumTerms);
573     }
574     else
575         return -1;
576
577     name[i++] = 0;
578
579     yaz_array_to_uri(&uri_args, encode, name, value);
580
581     hreq->method = "GET";
582
583     path = (char *)
584         odr_malloc(encode, strlen(hreq->path) +
585                    strlen(uri_args) + strlen(solr_op) + 5);
586
587     cp = strchr(hreq->path, '#');
588     if (cp)
589         *cp = '\0';
590     cp = strchr(hreq->path, '?');
591     if (cp)
592     {
593         *cp = '\0'; /* args in path */
594         path_args = cp + 1;
595     }
596     strcpy(path, hreq->path);
597     cp = strrchr(path, '/');
598     if (cp)
599     {
600         if (!strcmp(cp, "/select") || !strcmp(cp, "/"))
601             *cp = '\0';
602     }
603     strcat(path, "/");
604     strcat(path, solr_op);
605     strcat(path, "?");
606     if (path_args)
607     {
608         strcat(path, path_args);
609         strcat(path, "&");
610     }
611     strcat(path, uri_args);
612     hreq->path = path;
613
614     z_HTTP_header_add_content_type(encode, &hreq->headers,
615                                    "text/xml", charset);
616     return 0;
617 }
618
619
620 /*
621  * Local variables:
622  * c-basic-offset: 4
623  * c-file-style: "Stroustrup"
624  * indent-tabs-mode: nil
625  * End:
626  * vim: shiftwidth=4 tabstop=8 expandtab
627  */
628