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.
The only change
Section titled “The only change”https://es.example.com:9200https://machnosql.example.com:9200The address comes from the environment variable ELASTICSEARCH_URL, so switching to MachNoSQL changes configuration only.
export ELASTICSEARCH_URL='https://machnosql.example.com:9200'pip install -r requirements.txtpython app.pyCredentials come from ELASTICSEARCH_USERNAME and ELASTICSEARCH_PASSWORD.
Source
Section titled “Source”The program as it is kept and tested in the Mach Database NoSQL repository; highlighted lines read the connection setting.
"""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"])elasticsearch==9.5.1