Python Script for missing filed

Hi

I want to achive the following query in Python DSL

{
"query": {
"filtered":
{
"filter":
{
"and":
[
{ "terms": { "schoolID": 3456} },
{ "bool": {
"must": [
{ "term": { "facility": "1456" } },
{ "term": { "facility": "1457" } }
]
} },
{ "bool": {
"should": [
{ "range": {"fees": {"gte": min_fees, "lte": max_fees}} },
{"missing" : { "field" : "fees" }}
]
} },
{"geo_bounding_box":
{
"location":
{
"top_right":
{
"lat": X2,
"lon": y2
},
"bottom_left":
{
"lat": x1,
"lon": y1
}
}
}
}
]
}
}
}
}

What I have written in Python is

for facility in facilities:
facility_query.append({ "term": { "facility": int(facility) } })

s = Search(using=es, index="School", doc_type = "student")
.filter("term" , schoolID = schoolId )
.filter("geo_bounding_box", location = { "top_right" : {"lat": x2, "lon": y2 },
"bottom_left" : { "lat": x1, "lon": y1 }})
.query("range", fees = { "from": min_fees, "to": max_fees })

if facility:
s = s.query("bool", must= facility_query)

response = s.execute()

Two things I couldnt achieve

  1. In Price Range how to include missing field?
  2. Facility field I have to pass multiple values inside "must" bool query.

What needs to be altered in Python code to achieve it?

Hi Sivaprakash,

this is really more of a Python / design question than related to Elasticsearch. The Python Elasticsearch client just needs Python dicts for query documents and it seems to me you've built your own API on top of it which creates this data structure for you.

I'd build the query dict bottom up, so first build the individual clauses, like the school filter, the geo filter and so on, then connect them to via an and clause and build the overall query structure. This is something your Search class seems to be lacking yet.

You can look at the builder pattern and peek at the QueryBuilders Java API (and specifically the bool query API) for inspiration.

Daniel

1 Like