Elasticsearch构建动态查询 - python

时间:2016-04-17 22:19:38

标签: python elasticsearch elasticsearch-py

关于elasticsearch-py api的新手问题。我建立了一个名称,地址,电话号码等记录的索引,我可以使用python客户端进行查询 例如

`elasticsearch.search(index = "index_name", q= 'first_name:"JOHN"')` 

并获得适当的结果 但是,我想将查询作为字符串参数

first_name = "JOHN"
qu = "first_name:".join(first_name)
elasticsearch.search(index = 'index_name', q = qu)

,查询失败。有没有更好的方法来进行这些类型的动态查询?

2 个答案:

答案 0 :(得分:1)

我通常会将搜索查询构建为请求正文搜索。 https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-body.html

以下示例:

searchdata = essearch.search(index=indexname, body= {
    "query": {
        "filtered": {
          "query": {
            "query_string": {
              "query": "name:fred"
            }
          },
          "filter": {
            "bool": {
              "must": [

                {
                  "exists": {
                    "field": "fieldname"
                  }
                },
                {
                  "exists": {
                    "field": "secondfieldname"
                  }
                }

              ]
            }
          }
        }
      },
      "size": 5000,
      "sort": [
         {
            "loggeddate": {
               "order": "desc"
            }
         }
      ]
    }
           ) 

答案 1 :(得分:0)

您是否尝试过解压缩类似的字典:

mydict = {" firstname":firstname} elasticsearch.search(index =' index_name",** mydict)

甚至:

mydict = {" index":" index_name"," firstname":firstname} elasticsearch.search(** mydict)

mydict可以拥有你需要的任何键值对

值得一试