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