7cfd056e2b0dc01bd071736122ebe6ba38b66b5c
[yaz-moved-to-github.git] / src / solr.c
1 /* This file is part of the YAZ toolkit.
2  * Copyright (C) 1995-2013 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
22 #include "sru-p.h"
23
24 #define SOLR_MAX_PARAMETERS  100
25
26 #if YAZ_HAVE_XML2
27 #include <libxml/parser.h>
28 #include <libxml/tree.h>
29
30 static void extract_text_node(xmlNodePtr node, WRBUF wrbuf) {
31     xmlNodePtr child;
32     for (child = node->children; child ; child = child->next)
33     {
34         if (child->type == XML_TEXT_NODE)
35             wrbuf_puts(wrbuf, (const char *) child->content);
36     }
37 }
38
39 static int match_xml_node_attribute(
40     xmlNodePtr ptr,
41     const char *node_name, const char *attribute_name, const char *value)
42 {
43     const char *attribute_value;
44     // check if the node name matches
45     if (strcmp((const char*) ptr->name, node_name))
46         return 0;
47     if (attribute_name)
48     {
49         attribute_value = yaz_element_attribute_value_get(ptr, node_name,
50                                                           attribute_name);
51         if (attribute_value && !strcmp(attribute_value, value))
52             return 1;
53     }
54     else /* No attribute to check */
55         return 1;
56     return 0;
57 }
58
59 static void yaz_solr_decode_result_docs(ODR o, xmlNodePtr ptr,
60                                         Odr_int start,
61                                         Z_SRW_searchRetrieveResponse *sr)
62 {
63     xmlNodePtr node;
64     int offset = 0;
65     int i = 0;
66
67     sr->num_records = 0;
68     for (node = ptr->children; node; node = node->next)
69         if (node->type == XML_ELEMENT_NODE)
70             sr->num_records++;
71
72     if (sr->num_records)
73         sr->records = odr_malloc(o, sizeof(*sr->records) * sr->num_records);
74
75     for (node = ptr->children; node; node = node->next)
76     {
77         if (node->type == XML_ELEMENT_NODE)
78         {
79             Z_SRW_record *record = sr->records + i;
80             xmlBufferPtr buf = xmlBufferCreate();
81             xmlNode *tmp = xmlCopyNode(node, 1);
82
83             xmlNodeDump(buf, tmp->doc, tmp, 0, 0);
84
85             xmlFreeNode(tmp);
86
87             record->recordSchema = 0;
88             record->recordPacking = Z_SRW_recordPacking_XML;
89             record->recordData_len = buf->use;
90             record->recordData_buf = odr_malloc(o, buf->use + 1);
91             memcpy(record->recordData_buf, buf->content, buf->use);
92             record->recordData_buf[buf->use] = '\0';
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 = yaz_use_attribute_create(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     xmlAttr *attr;
268     char *pos;
269     int i = 0;
270
271     /* find the actual list */
272     for (node = ptr->children; node; node = node->next)
273         if (node->type == XML_ELEMENT_NODE) {
274             ptr = node;
275             break;
276         }
277
278     scr->num_terms = 0;
279     for (node = ptr->children; node; node = node->next)
280         if (node->type == XML_ELEMENT_NODE && !strcmp((const char *) node->name, "int"))
281             scr->num_terms++;
282
283     if (scr->num_terms)
284         scr->terms = odr_malloc(o, sizeof(*scr->terms) * scr->num_terms);
285
286     for (node = ptr->children; node; node = node->next)
287     {
288         if (node->type == XML_ELEMENT_NODE && !strcmp((const char *) node->name, "int"))
289         {
290             Z_SRW_scanTerm *term = scr->terms + i;
291
292             Odr_int count = 0;
293             const char *val = get_facet_term_count(node, &count);
294
295             term->numberOfRecords = odr_intdup(o, count);
296
297             /* if val contains a ^ then it is probably term<^>display term so separate them. This is due to
298              * SOLR not being able to encode them into 2 separate attributes.
299              */
300             pos = strchr(val, '^');
301             if (pos != NULL) {
302                 term->displayTerm = odr_strdup(o, pos + 1);
303                 *pos = '\0';
304                 term->value = odr_strdup(o, val);
305                 *pos = '^';
306             } else {
307                 term->value = odr_strdup(o, val);
308                 term->displayTerm = NULL;
309             }
310             term->whereInList = NULL;
311
312             i++;
313         }
314     }
315
316     if (scr->num_terms)
317         return 0;
318     return -1;
319 }
320 #endif
321
322 int yaz_solr_decode_response(ODR o, Z_HTTP_Response *hres, Z_SRW_PDU **pdup)
323 {
324 #if YAZ_HAVE_XML2
325     const char *content_buf = hres->content_buf;
326     int content_len = hres->content_len;
327     xmlDocPtr doc = xmlParseMemory(content_buf, content_len);
328     int ret = 0;
329     xmlNodePtr ptr = 0;
330     Z_SRW_PDU *pdu;
331     Z_SRW_searchRetrieveResponse *sr = NULL;
332     Z_SRW_scanResponse *scr = NULL;
333
334     if (!doc)
335     {
336         ret = -1;
337     }
338     if (doc)
339     {
340         xmlNodePtr root = xmlDocGetRootElement(doc);
341         if (!root)
342         {
343             ret = -1;
344         }
345         else if (strcmp((const char *) root->name, "response"))
346         {
347             ret = -1;
348         }
349         else
350         {
351             /** look for result (required) and facets node (optional) */
352             int rc_result = -1;
353             int rc_facets = 0;
354             for (ptr = root->children; ptr; ptr = ptr->next)
355             {
356                 if (ptr->type == XML_ELEMENT_NODE &&
357                     !strcmp((const char *) ptr->name, "result")) {
358                         pdu = yaz_srw_get(o, Z_SRW_searchRetrieve_response);
359                         sr = pdu->u.response;
360                         rc_result = yaz_solr_decode_result(o, ptr, sr);
361                 }
362                 if (ptr->type == XML_ELEMENT_NODE &&
363                     match_xml_node_attribute(ptr, "lst", "name", "terms")) {
364                         pdu = yaz_srw_get(o, Z_SRW_scan_response);
365                         scr = pdu->u.scan_response;
366                         rc_result = yaz_solr_decode_scan_result(o, ptr, scr);
367                 }
368                 /* TODO The check on hits is a work-around to avoid garbled facets on zero results from the SOLR server.
369                  * The work-around works because the results is before the facets in the xml. */
370                 if (sr) {
371                     if (rc_result == 0 &&  *sr->numberOfRecords > 0 &&
372                         match_xml_node_attribute(ptr, "lst", "name", "facet_counts"))
373                             rc_facets =  yaz_solr_decode_facet_counts(o, ptr, sr);
374                     if (rc_result == 0 &&  *sr->numberOfRecords == 0 &&
375                         match_xml_node_attribute(ptr, "lst", "name", "spellcheck"))
376                             rc_facets =  yaz_solr_decode_spellcheck(o, ptr, sr);
377                 }
378
379             }
380             ret = rc_result + rc_facets;
381         }
382     }
383     if (doc)
384         xmlFreeDoc(doc);
385     if (ret == 0)
386         *pdup = pdu;
387     return ret;
388 #else
389     return -1;
390 #endif
391 }
392
393 static int yaz_solr_encode_facet_field(
394     ODR encode, char **name, char **value, int *i,
395     Z_FacetField *facet_field)
396 {
397     Z_AttributeList *attribute_list = facet_field->attributes;
398     struct yaz_facet_attr attr_values;
399     yaz_facet_attr_init(&attr_values);
400     yaz_facet_attr_get_z_attributes(attribute_list, &attr_values);
401     // TODO do we want to support server decided
402
403     if (attr_values.errcode)
404         return -1;
405     if (attr_values.useattr)
406     {
407         WRBUF wrbuf = wrbuf_alloc();
408         wrbuf_puts(wrbuf, (char *) attr_values.useattr);
409         yaz_add_name_value_str(encode, name, value, i,
410                                "facet.field",
411                                odr_strdup(encode, wrbuf_cstr(wrbuf)));
412         if (attr_values.limit > 0)
413         {
414             WRBUF wrbuf2 = wrbuf_alloc();
415             Odr_int olimit;
416             wrbuf_puts(wrbuf2, "f.");
417             wrbuf_puts(wrbuf2, wrbuf_cstr(wrbuf));
418             wrbuf_puts(wrbuf2, ".facet.limit");
419             olimit = attr_values.limit;
420             yaz_add_name_value_int(encode, name, value, i,
421                                    odr_strdup(encode, wrbuf_cstr(wrbuf2)),
422                                    &olimit);
423             wrbuf_destroy(wrbuf2);
424         }
425         wrbuf_destroy(wrbuf);
426     }
427     return 0;
428 }
429
430 static int yaz_solr_encode_facet_list(
431     ODR encode, char **name, char **value,
432     int *i, Z_FacetList *facet_list)
433 {
434     int index;
435     for (index = 0; index < facet_list->num; index++)
436     {
437         int r = yaz_solr_encode_facet_field(encode, name, value, i,
438                                             facet_list->elements[index]);
439         if (r)
440             return -1;
441
442     }
443     return 0;
444 }
445
446 int yaz_solr_encode_request(Z_HTTP_Request *hreq, Z_SRW_PDU *srw_pdu,
447                             ODR encode, const char *charset)
448 {
449     const char *solr_op = 0;
450     //TODO Change. not a nice hard coded, unchecked limit.
451     char *name[SOLR_MAX_PARAMETERS], *value[SOLR_MAX_PARAMETERS];
452     char *uri_args;
453     char *path;
454     char *q;
455     char *pos;
456     int i = 0;
457
458     z_HTTP_header_add_basic_auth(encode, &hreq->headers,
459                                  srw_pdu->username, srw_pdu->password);
460     if (srw_pdu->which == Z_SRW_searchRetrieve_request)
461     {
462         Z_SRW_searchRetrieveRequest *request = srw_pdu->u.request;
463         solr_op = "select";
464         switch (srw_pdu->u.request->query_type)
465         {
466         case Z_SRW_query_type_pqf:
467             yaz_add_name_value_str(encode, name, value, &i,
468                                    "q", request->query.pqf);
469             break;
470         case Z_SRW_query_type_cql:
471             yaz_add_name_value_str(encode, name, value, &i,
472                                    "q", request->query.cql);
473             break;
474         default:
475             return -1;
476         }
477         if (srw_pdu->u.request->startRecord)
478         {
479             Odr_int start = *request->startRecord - 1;
480             yaz_add_name_value_int(encode, name, value, &i,
481                                    "start", &start);
482         }
483         yaz_add_name_value_int(encode, name, value, &i,
484                                "rows", request->maximumRecords);
485         yaz_add_name_value_str(encode, name, value, &i,
486                                "fl", request->recordSchema);
487
488         switch(srw_pdu->u.request->sort_type)
489         {
490         case Z_SRW_sort_type_none:
491             break;
492         case Z_SRW_sort_type_sort:
493             yaz_add_name_value_str(encode, name, value, &i, "sort",
494                                    srw_pdu->u.request->sort.sortKeys);
495             break;
496         }
497         if (request->facetList)
498         {
499             Z_FacetList *facet_list = request->facetList;
500             yaz_add_name_value_str(encode, name, value, &i, "facet", "true");
501             yaz_add_name_value_str(encode, name, value, &i, "facet.mincount", "1");
502             if (yaz_solr_encode_facet_list(encode, name, value, &i, facet_list))
503                 return -1;
504         }
505     }
506     else if (srw_pdu->which == Z_SRW_scan_request) {
507         Z_SRW_scanRequest *request = srw_pdu->u.scan_request;
508         solr_op = "terms";
509         switch (srw_pdu->u.scan_request->query_type)
510         {
511             case Z_SRW_query_type_pqf:
512                 yaz_add_name_value_str(encode, name, value, &i,
513                                        "terms.fl", request->scanClause.pqf);
514                 yaz_add_name_value_str(encode, name, value, &i,
515                                        "terms.lower", request->scanClause.pqf);
516                 break;
517             case Z_SRW_query_type_cql:
518                 q = request->scanClause.cql;
519                 pos = strchr(q, ':');
520                 if (pos != NULL) {
521                                         yaz_add_name_value_str(encode, name, value, &i,
522                                                                                    "terms.lower", odr_strdup(encode, pos + 1));
523                                         *pos = '\0';
524                                         yaz_add_name_value_str(encode, name, value, &i,
525                                                                                    "terms.fl", odr_strdup(encode, q));
526                                         *pos = ':';
527                 } else {
528                                         yaz_add_name_value_str(encode, name, value, &i,
529                                                                                    "terms.lower", odr_strdup(encode, q));
530                 }
531                 break;
532             default:
533                 return -1;
534         }
535         yaz_add_name_value_str(encode, name, value, &i,
536                                "terms.sort", "index");
537         yaz_add_name_value_int(encode, name, value, &i,
538                                "terms.limit", request->maximumTerms);
539     }
540     else
541         return -1;
542
543     if (srw_pdu->extra_args)
544     {
545         Z_SRW_extra_arg *ea = srw_pdu->extra_args;
546         for (; ea && i < SOLR_MAX_PARAMETERS; ea = ea->next)
547         {
548             name[i] = ea->name;
549             value[i] = ea->value;
550             i++;
551         }
552     }
553
554     name[i++] = 0;
555
556     yaz_array_to_uri(&uri_args, encode, name, value);
557
558     hreq->method = "GET";
559
560     path = (char *)
561         odr_malloc(encode, strlen(hreq->path) +
562                    strlen(uri_args) + strlen(solr_op) + 4);
563
564     sprintf(path, "%s/%s?%s", hreq->path, solr_op, uri_args);
565     hreq->path = path;
566
567     z_HTTP_header_add_content_type(encode, &hreq->headers,
568                                    "text/xml", charset);
569     return 0;
570 }
571
572
573 /*
574  * Local variables:
575  * c-basic-offset: 4
576  * c-file-style: "Stroustrup"
577  * indent-tabs-mode: nil
578  * End:
579  * vim: shiftwidth=4 tabstop=8 expandtab
580  */
581