How to connect to Elasticsearch using Python?
Published on Aug. 22, 2023, 12:19 p.m.
To connect to Elasticsearch using Python, you can use the Elasticsearch client library for Python. Here’s an example code snippet to create a connection with Elasticsearch:
from elasticsearch import Elasticsearch
es = Elasticsearch(['http://localhost:9200'])
In this case, we’re creating a new instance of the Elasticsearch
class and passing it the URL of the Elasticsearch cluster we want to connect to.
You can also specify additional configuration options or credentials if necessary.
To test if the connection was successful, you can use the pinging the instance method:
print(es.ping())
This will return True
if the connection was successful.
To perform a simple search in Elasticsearch using Python, you can use the search
method provided by the Elasticsearch client library. Here is an example code snippet:
from elasticsearch import Elasticsearch
# create an Elasticsearch client instance
es = Elasticsearch(['http://localhost:9200'])
# define the search query
query = {
"query": {
"match": {
"description": "python"
}
}
}
# perform the search and get the results
results = es.search(index="my_index", body=query)
# print the results
for result in results['hits']['hits']:
print(result['_source'])
In this example, we’re searching the my_index
index for documents that contain the word “python” in their “description” field. The search
method returns a dictionary containing the matching documents, which we then iterate over and print.
You can modify the search query to match your specific search requirements. Additionally, you can specify additional search parameters, such as sorting and filtering, as needed.
How to apply filters to search queries in Elasticsearch using Python?
To apply filters to search queries in Elasticsearch using Python, you can use the filter
parameter in the search query. Here’s an example code snippet:
from elasticsearch import Elasticsearch
# create an Elasticsearch client instance
es = Elasticsearch(['http://localhost:9200'])
# define the search query with a filter
query = {
"query": {
"bool": {
"must": {
"match": {
"description": "python"
}
},
"filter": {
"range": {
"price": {
"gte": 10,
"lte": 100
}
}
}
}
}
}
# perform the search and get the results
results = es.search(index="my_index", body=query)
# print the results
for result in results['hits']['hits']:
print(result['_source'])
In this example, we’re searching the my_index
index for documents containing the word “python” in their “description” field, and with a “price” field that falls within the range of 10 to 100. The filter
parameter is used to specify the range filter.
You can also use other types of filters, such as term filters or bool filters, depending on your specific search requirements.