Python中的Elasticsearch多字段查询请求

时间:2020-09-26 15:21:02

标签: python elasticsearch kibana

我是Elasticsearch和Python的初学者,并且在Elasticsearch中创建了包含一些数据的索引,并且我想使用python对这些数据执行查询请求。这是我在Kibana的开发工具中创建的数据映射:

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"
      }
    }
  }
}

这是我的Python代码,在其中,我们给它提供一个关键字和一个类别编号,并且它必须为匹配的关键字检入弹性数据的标题,线索和内容字段,并使用数据类别编号,并返回/打印出符合以下条件的任何对象:

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)

但是当我将数据提供给输入时,我会收到此错误:

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

我在做什么错了?

编辑:关键字必须包含在标题,线索和内容中,但不必与它们相同

1 个答案:

答案 0 :(得分:0)

您的 multi_match 查询语法在这里是错误的,我还认为您需要类似的东西,查看更多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" ]
          }
        }
      ]
    }
  }
}