Elasticsearch query / ricerca multipla con Python

Sep 26 2020

Sono nuovo di Python ed Elasticsearch e ho creato un indice con alcuni dati in Elasticsearch e voglio eseguire una query su di essi con Python in base ad alcuni filtri ricevuti dall'utente (parola chiave, categoria)

from elasticsearch import Elasticsearch
import json,requests

es = Elasticsearch(HOST="http://localhost", PORT=9200)
es = Elasticsearch()

def QueryMaker (keyword,category):
   response = es.search(index="main-news-test-data",body={"from":0,"size":10000,"query":{
       "bool": {
      "should": [
        {
          "multi_match" : {
            "query":      keyword,
            "fields":     [ "content", "title","lead" ]
          }
        },
        {
          "multi_match" : {
            "query":      category,
            "fields":     [ "category" ]
          }
        }
      ]
    }
   }})
   return(response)

def Mapper (category):
 fhandle = open('categories.txt','r', encoding="utf8")
 for line in fhandle:
     line = line.rstrip()
     items = line.split(';')
     if f'"{category}"' in items:
         category = items[0]
         return(category)

if __name__ == '__main__': 
    keyword = input('Enter Keyword: ')
    print(type(keyword))
    category = input('Enter Category: ')
    print(type(category))
    #startDate = input('Enter StartDate: ')
    #endDate = input('Enter EndDate: ')
    
    mapCategory = Mapper(category)
    if mapCategory is not None:
      mapCategory = mapCategory.replace("%","")
      data = QueryMaker(keyword,mapCategory)
      print(data)
    else:
      data = QueryMaker(keyword,mapCategory)
      print(data)

Il problema è che questo programma restituisce solo i dati corrispondenti solo se i 2 campi sono pieni, ma voglio che restituisca anche i dati se 1 campo come categoria è vuoto. Quando la parola chiave è vuota è simile '' e non restituisce nulla e quando la categoria è vuota ricevo questo errore:

elasticsearch.exceptions.RequestError: RequestError(400, 'x_content_parse_exception', '[multi_match] unknown token [VALUE_NULL] after [query]')   

Cosa sto facendo di sbagliato e come posso correggere il mio filtro di ricerca?

Risposte

ESCoder Sep 27 2020 at 01:57

Aggiunta di un esempio funzionante con dati di indice, query di ricerca e risultati della ricerca

Secondo i tuoi commenti sopra menzionati, se il contentcampo non contiene keyworde se il categorycampo contiene category, la query di ricerca verrà eseguita per il categorycampo. Ciò può essere ottenuto utilizzandominimum_should_match

Dati indice:

{
    "content": "keyword a",
    "title": "b",
    "lead": "c",
    "category": "d"
}
{
    "content": "a",
    "title": "b",
    "lead": "c",
    "category": "category"
}
{
    "content": "keyword a",
    "title": "b",
    "lead": "c",
    "category": "category"
}

Query di ricerca:

{
  "query": {
    "bool": {
      "should": [
        {
          "multi_match": {
            "query": "keyword",
            "fields": [
              "content",
              "title",
              "lead"
            ]
          }
        },
        {
          "multi_match": {
            "query": "category",
            "fields": [
              "category"
            ]
          }
        }
      ],
      "minimum_should_match":1
    }
  }
}

Risultato della ricerca:

"hits": [
      {
        "_index": "stof_64081587",
        "_type": "_doc",
        "_id": "3",
        "_score": 0.9666445,
        "_source": {
          "content": "keyword a",
          "title": "b",
          "lead": "c",
          "category": "category"
        }
      },
      {
        "_index": "stof_64081587",
        "_type": "_doc",
        "_id": "2",
        "_score": 0.60996956,
        "_source": {
          "content": "keyword a",
          "title": "b",
          "lead": "c",
          "category": "d"
        }
      },
      {
        "_index": "stof_64081587",
        "_type": "_doc",
        "_id": "1",
        "_score": 0.35667494,
        "_source": {
          "content": "a",
          "title": "b",
          "lead": "c",
          "category": "category"
        }
      }
    ]