Home > other >  How to make elasticsearch query with Python lists
How to make elasticsearch query with Python lists

Time:02-21

I have dynamic lists returning from a microservice.

For example,

list1 = ["abc","def","efg"]

And I'm creating another microservice that does elasticsearch queries with Python.

Let's say I have an elasticsearch field called word and the type of the value of this field is string.

I want to return items where this field value is equal to any element in the list.

Let's say we have an elasticsearch index named some_index that looks like this

http://127.0.0.1:9200/some_index/_search?

[
    {
        "_source": {
            "word": "bca"
        }
    },
    {
        "_source": {
            "word": "abc"
        }
    },
    {
        "_source": {
            "word": "efg"
        }
    },
    {
        "_source": {
            "word": "xyz"
        }
    },
    {
        "_source": {
            "word": "mnt"
        }
    },
]

When we run this code template:

from elasticsearch import Elasticsearch

es = Elasticsearch()

list1 = ["abc","def","efg"]

es_query = {<the query i have to write>}

search = es.search(index="some_index", query=es_query)

print(search['hits']['hits'])

I want something like this to return:

[
    {
        "_source": {
            "word": "abc"
        }
    },
    {
        "_source": {
            "word": "efg"
        }
    }
]

What is the query I have to write or do you have any advice for this situation?

CodePudding user response:

I believe you are looking for the terms query.

GET /71196041/_search
{
  "query": {
    "terms": {
      "word.keyword": ["abc","def","efg"]
    }
  }
}

Which in you code should look like:

from elasticsearch import Elasticsearch

es = Elasticsearch()

list1 = ["abc","def","efg"]

es_query = {
    "terms": {
      "word.keyword": list1
    }
}

search = es.search(index="some_index", query=es_query)

print(search['hits']['hits'])
  • Related