Python Elasticsearch is a Python library that provides a client for Elasticsearch, a distributed search and analytics engine. It allows you to interact with Elasticsearch from Python code, and to perform all of the common Elasticsearch operations, such as:
- Creating and managing indexes
- Indexing documents
- Searching for documents
- Updating and deleting documents
To use Python Elasticsearch, you first need to install the elasticsearch-py
package. You can do this with pip:
pip install elasticsearch-py
Once the package is installed, you can import the elasticsearch
module and create a client:
Python
import elasticsearch
es = elasticsearch.Elasticsearch()
The Elasticsearch client object provides a number of methods for interacting with Elasticsearch. For example, to index a document, you can use the index()
method:
Python
document = {
"title": "My document title",
"body": "This is the body of my document."
}
es.index(index="my_index", doc_type="my_type", body=document)
To search for documents, you can use the search()
method:
Python
query = {
"query": {
"match": {
"title": "My document title"
}
}
}
results = es.search(index="my_index", doc_type="my_type", body=query)
The results
variable will contain a list of documents that match the query.
For more information on using Python Elasticsearch, please see the official documentation: https://elasticsearch-py.readthedocs.io/en/7.x/.
Here is a simple example of a Python script that uses Elasticsearch to index and search for documents:
Python
import elasticsearch
es = elasticsearch.Elasticsearch()
# Create an index
es.indices.create(index="my_index")
# Index a document
document = {
"title": "My document title",
"body": "This is the body of my document."
}
es.index(index="my_index", doc_type="my_type", body=document)
# Search for documents
query = {
"query": {
"match": {
"title": "My document title"
}
}
}
results = es.search(index="my_index", doc_type="my_type", body=query)
# Print the results
for hit in results["hits"]["hits"]:
print(hit["_source"]["title"])
This script will create an index called my_index
, index a single document to the index, and then search for documents that match the query title:My document title
. The results of the search will be printed to the console.
Python Elasticsearch is a powerful tool for interacting with Elasticsearch from Python code. It allows you to easily perform all of the common Elasticsearch operations, and to build complex search and analytics applications.