AI Hints
Home›Elasticsearch Tutorial›Searching and Errors in Python
Elasticsearch · Lesson 91 of 120

Searching from Python

Queries as dictionaries.

⏱ 2 min read▶ Video at 1:25:31🎓 Free
Watch this lesson in the Elasticsearch courseWatch on YouTube ↗Full Elasticsearch course

Every query you wrote in the console works in Python too. The JSON becomes a Python dictionary, and the response comes back as one.

  • Same queries
  • JSON to dict
  • Response as dict

A bool query in Python

Search takes query as a keyword argument. It's the same bool query as before, written as a dictionary. We loop over the hits and print each name and price. Run it. Tents under three hundred dollars.

search.pypython
from elasticsearch import Elasticsearch

es = Elasticsearch("http://localhost:9200")

resp = es.search(index="products", query={
    "bool": {
        "must": {"match": {"name": "tent"}},
        "filter": {"range": {"price": {"lt": 300}}}}},
    size=3, source=["name", "price"])

print("Total:", resp["hits"]["total"]["value"])
for hit in resp["hits"]["hits"]:
    print(hit["_source"]["name"], hit["_source"]["price"])
Output
Total: 4
Basecamp Family Tent 175.99
Basecamp 2-Person Tent 237.99
Basecamp 3-Person Tent 288.99
Also uses _load
catalog

Tips

Pass size, sort, source and aggregations as keyword arguments. Hits total tells you how many matched. And for a user's search box, build the query dictionary from their input, never by gluing strings together.

keyvalue
size, sortkeyword args
sourcefields to return
hits.totalhow many
User inputinto the dict

Summary

Search from Python with the same queries, written as dictionaries. Next, aggregations in Python.

Key takeaways
  • es.search
  • query=
  • hits
Next up: Aggregations in Python — numbers for your app