Skip to content

Elasticsearch with elasticsearch-py (Python)

Uses elasticsearch-py 9.5. The code is an ordinary application for the original database; nothing in it knows about MachNoSQL.

https://es.example.com:9200
https://machnosql.example.com:9200

The address comes from the environment variable ELASTICSEARCH_URL, so switching to MachNoSQL changes configuration only.

Terminal window
export ELASTICSEARCH_URL='https://machnosql.example.com:9200'
pip install -r requirements.txt
python app.py

Credentials come from ELASTICSEARCH_USERNAME and ELASTICSEARCH_PASSWORD.

The program as it is kept and tested in the Mach Database NoSQL repository; highlighted lines read the connection setting.

app.py
"""Product search on Elasticsearch, unchanged on MachNoSQL."""
import os
from elasticsearch import Elasticsearch, helpers
es = Elasticsearch(
os.environ["ELASTICSEARCH_URL"],
basic_auth=(os.environ["ELASTICSEARCH_USERNAME"], os.environ["ELASTICSEARCH_PASSWORD"]),
)
if not es.indices.exists(index="products"):
es.indices.create(
index="products",
mappings={"properties": {"name": {"type": "text"}, "brand": {"type": "keyword"}, "price": {"type": "float"}}},
)
helpers.bulk(
es,
[
{"_index": "products", "_id": "1", "name": "mechanical keyboard", "brand": "keyco", "price": 89.0},
{"_index": "products", "_id": "2", "name": "wireless keyboard", "brand": "typer", "price": 49.0},
{"_index": "products", "_id": "3", "name": "gaming mouse", "brand": "keyco", "price": 39.0},
],
)
es.indices.refresh(index="products")
hits = es.search(index="products", query={"match": {"name": "keyboard"}})["hits"]["hits"]
for hit in hits:
print(hit["_score"], hit["_source"]["name"])
brands = es.search(index="products", size=0, aggs={"brands": {"terms": {"field": "brand"}}})
print(brands["aggregations"]["brands"]["buckets"])
requirements.txt
elasticsearch==9.5.1