user3351750
user3351750

Reputation: 927

AND query in elasticsearch python

Records Stored in Elasticsearch:

"hits" : [ {
      "_index" : "test",
      "_type" : "test_doc",
      "_id" : "AVUHBSESPB1nLi5k2Dxp",
      "_score" : 1.0,
      "_source":{"valid": true,"action_taken": false}
    }, {
      "_index" : "test",
      "_type" : "test_doc",
      "_id" : "AVUHBI1IPB1nLi5k2Dxo",
      "_score" : 1.0,
      "_source":{"valid": true,"action_taken": false}
    }, {
      "_index" : "test",
      "_type" : "test_doc",
      "_id" : "AVUHWFipPB1nLi5k2Dxu",
      "_score" : 1.0,
      "_source":{"valid": false,"action_taken": false}
    } ]

We need to find those records whose valid is true and action_taken is false in python script using elasticsearch python package.

We are trying to do the same using

resp = ES.search(index='test', doc_type='test_doc', q='action_taken:0 valid:1)

However on execution, it returns all the records. Is there any possible way to do the same using search.

PS: I am trying to write an API call which searches the records based on the search condition provided as json data in the request.

Upvotes: 1

Views: 1936

Answers (1)

Mihai Ionescu
Mihai Ionescu

Reputation: 978

The request you're sending to ElasticSearch doesn't look like a valid query. ES requires queries to be formatted in a specific way:

"query": {
    "match": {
        "content": term
    }
}

Based on this, I believe your need to change the q param.

For ElasticSearch pre 2.x, the query should make use of the filtered andfilter options. The query string is more similar to the SQL queries, so and, or filters are available (docs):

"query": {
    "filtered": {
        "filter": {
           "and": [
                {"term": { "action_taken": 0 }},
                {"term": { "valid": 0 }}
            ]
        }
    }
}

Starting ElasticSearch 2.3, the and query is deprecated, and bool is suggested instead:

"query": {
    "bool": {
        "must": [
            {"term": { "action_taken": 0 }},
            {"term": { "valid": 0 }}
         ]
    }
}

Here is the link to the 2.3 docs

Hope this helps. Let me know.

Upvotes: 1

Related Questions