Get started with the serverless Python client

edit

Get started with the serverless Python client

edit

[preview] This functionality is in technical preview and may be changed or removed in a future release. Elastic will work to fix any issues, but features in technical preview are not subject to the support SLA of official GA features.

This page guides you through the installation process of the Python client for Elasticsearch Serverless, shows you how to initialize the client, and how to perform basic Elasticsearch operations with it.

Requirements
edit
  • Python 3.7 or higher
  • pip
Documentation
edit

Find the full documentation for the Python client on readthedocs.

Installation
edit
Using the command line
edit

You can install the Python client with the following commands:

python -m pip install elasticsearch-serverless
Initialize the client
edit

Initialize the client using your API key and Elasticsearch Endpoint:

from elasticsearch_serverless import Elasticsearch

client = Elasticsearch(
    "https://...",  # Your project's Elasticsearch Endpoint
    api_key='api-key',  # API key for your project
)

To get API keys or the Elasticsearch Endpoint for a project, see Get started.

Using the API
edit

After you’ve initialized the client, you can start ingesting documents. You can use the bulk API for this. This API enables you to index, update, and delete several documents in one request.

Creating an index and ingesting documents
edit

You can call the bulk API with a body parameter, an array of hashes that define the action, and a document.

The following is an example of indexing some classic books into the books index:

from datetime import datetime

client.bulk(
    body=[
        {"index": {"_index": "books", "_id": "1"}},
        {"title": "Infinite Jest", "author": "David Foster Wallace", "published_on": datetime(1996, 2, 1)},
        {"index": {"_index": "books", "_id": "2"}},
        {"title": "Ulysses", "author": "James Joyce", "published_on": datetime(1922, 2, 2)},
        {"index": {"_index": "books", "_id": "3"}},
        {"title": "Just Kids", "author": "Patti Smith", "published_on": datetime(2010, 1, 19)},
    ],
)
Getting documents
edit

You can get documents by using the following code:

response = client.get(index="books", id="1")
print(response.body)
Searching
edit

Now that some data is available, you can search your documents using the search API:

response = client.search(index="books", query={
    "match": {
        "title": "infinite"
    }
})

for hit in response["hits"]["hits"]:
    print(hit["_source"])
Updating a document
edit

You can call the update API to update a document:

client.update(index="books", id="2", doc={
    "author": "James Augustine Aloysius Joyce",
    "pages": 732,
})
Deleting a document
edit

You can call the delete API to delete a document:

client.delete(index="books", id="3")
Deleting an index
edit
client.indices.delete(index="books")