Ankit Ankit - 7 months ago 90
Python Question

Python Elasticsearch DSL query value from a list

I am using Python's Elasticsearch DSL package:
http://elasticsearch-dsl.readthedocs.org/en/latest/search_dsl.html

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': {'doc.country': [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

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': {'doc.country': country}})

s = s.query(Q('bool', must=must, should=should, minimum_should_match=1))
response = s.execute()
Comments