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