Search code examples
pythonelasticsearchkibana

Elasticsearch multi field query request in Python


I'm a beginner in Elasticsearch and Python and I have an index created in Elasticsearch with some data, and I want to perform a query request on those data with python. This is my data mapping created in Kibana's Dev tools:

PUT /main-news-test-data
{
  "mappings": {
    "properties": {
      "content": {
        "type": "text"
      },
      "title": {
        "type": "text"
      },
      "lead": {
        "type": "text"
      },
      "agency": {
        "type": "keyword"
      },
      "date_created": {
        "type": "date"
      },
      "url": {
        "type": "keyword"
      },
      "image": {
        "type": "keyword"
      },
      "category": {
        "type": "keyword"
      },
      "id":{
        "type": "keyword"
      }
    }
  }
}

and here is my Python code, in which we give it a keyword and a category number and it has to check in title, lead and content fields of the elastic data for the matching keyword and also check the entered category number with the data category number and return/print out any object that matches this criteria:

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":5,"query":{"multi_match":{
       "content":keyword,"category":category,"title":keyword,"lead":keyword}}})
   return(response)

if __name__ == '__main__': 
    keyword = input('Enter Keyword: ')
    category = input('Enter Category: ')
    #startDate = input('Enter StartDate: ')
    #endDate = input('Enter EndDate: ')
    data = QueryMaker(keyword,category)
    print(data)

but I receive this error when I give the data to the input:

elasticsearch.exceptions.RequestError: RequestError(400, 'parsing_exception', '[multi_match] query does not support [content]')

What am I doing wrong?

Edit: the keyword has to be included in the title, lead and content but it doesn't have to be the same as them


Solution

  • Your multi_match query syntax is wrong here, also I think you need something like this, See more: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-multi-match-query.html

    {
      "from":0,
      "size":5,
      "query": {
        "bool": {
          "should": [
            {
              "multi_match" : {
                "query":      keyword,
                "fields":     [ "content", "title","lead" ]
              }
            },
            {
              "multi_match" : {
                "query":      category,
                "fields":     [ "category" ]
              }
            }
          ]
        }
      }
    }