Ankit Ankit - 1 year ago 216
Python Question

Python Elasticsearch DSL query value from a list

I am using Python's Elasticsearch DSL package:

My sample elasticsearch entry looks like:

"_index" : "users",
"_type" : "player",
"_id" : "1",
"_version" : 5,
"found" : true,
"_source":{"doc": {"weight": 92, "height": 184, "gender": "male", "firstname": "John", "lastname": "Smith", "age": 31, "country": "France"}}

and I'm trying to fetch all entries that
firstname = "John*"
country in the list of
[France, Australia]
. Here's my code:

firstname = 'John'
s = Search(index='users').using(elasticsearch)
must = [
{'match': {'doc.firstname': {'query': firstname + '*', 'boost': 2}}},
{'terms': {'': [u'France', u'Australia']}}]

s = s.query(Q('bool', must=must))
response = s.execute()

it returns empty results, what am I doing wrong? I'm using the suggestion from here:
Elasticsearch match list against field

I'm new to Elasticsearch, still a little confused with where we use query vs filter.

Answer Source

I used the should param for this instead:

firstname = 'John'
s = Search(index='users').using(elasticsearch)
must = [
  {'match': {'doc.firstname': {'query': firstname + '*', 'boost': 2}}}]

should = []
for country in countries:
  should.append({'match': {'': country}})

s = s.query(Q('bool', must=must, should=should, minimum_should_match=1))
response = s.execute()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download