From 794341dd05305885c70597970c0a2dea2585924e Mon Sep 17 00:00:00 2001 From: Iulia Feroli Date: Tue, 26 Mar 2024 15:26:26 +0100 Subject: [PATCH] Rename es to client in examples for consistency (#2486) --- .../3d1ff6097e2359f927c88c2ccdb36252.asciidoc | 2 +- docs/guide/configuration.asciidoc | 50 +++++++++---------- docs/guide/connecting.asciidoc | 12 ++--- docs/guide/examples.asciidoc | 10 ++-- docs/guide/integrations.asciidoc | 8 +-- docs/guide/overview.asciidoc | 6 +-- docs/sphinx/async.rst | 26 +++++----- docs/sphinx/helpers.rst | 4 +- docs/sphinx/index.rst | 10 ++-- elasticsearch/_async/helpers.py | 2 +- elasticsearch/helpers/actions.py | 2 +- examples/fastapi-apm/app.py | 26 +++++----- 12 files changed, 80 insertions(+), 78 deletions(-) diff --git a/docs/examples/3d1ff6097e2359f927c88c2ccdb36252.asciidoc b/docs/examples/3d1ff6097e2359f927c88c2ccdb36252.asciidoc index 93e97eaeb..0f131773f 100644 --- a/docs/examples/3d1ff6097e2359f927c88c2ccdb36252.asciidoc +++ b/docs/examples/3d1ff6097e2359f927c88c2ccdb36252.asciidoc @@ -2,6 +2,6 @@ [source, python] ---- -resp = es.info() +resp = client.info() print(resp) ---- diff --git a/docs/guide/configuration.asciidoc b/docs/guide/configuration.asciidoc index cb467dc0d..5455e5ef7 100644 --- a/docs/guide/configuration.asciidoc +++ b/docs/guide/configuration.asciidoc @@ -20,7 +20,7 @@ If you have your own CA bundle to use you can configure via the `ca_certs` param [source,python] ------------------------------------ -es = Elasticsearch( +client = Elasticsearch( "https://...", ca_certs="/path/to/certs.pem" ) @@ -32,7 +32,7 @@ In Python 3.9 and earlier only the leaf certificate will be verified but in Pyth [source,python] ------------------------------------ -es = Elasticsearch( +client = Elasticsearch( "https://...", ssl_assert_fingerprint=( "315f5bdb76d078c43b8ac0064e4a0164612b1fce77c869345bfc94c75894edd3" @@ -44,7 +44,7 @@ To disable certificate verification use the `verify_certs=False` parameter. This [source,python] ------------------------------------ -es = Elasticsearch( +client = Elasticsearch( "https://...", verify_certs=False ) @@ -59,7 +59,7 @@ Configuring the minimum TLS version to connect to is done via the `ssl_version` ------------------------------------ import ssl -es = Elasticsearch( +client = Elasticsearch( ..., ssl_version=ssl.TLSVersion.TLSv1_2 ) @@ -72,7 +72,7 @@ Elasticsearch can be configured to authenticate clients via TLS client certifica [source,python] ------------------------------------ -es = Elasticsearch( +client = Elasticsearch( ..., client_cert="/path/to/cert.pem", client_key="/path/to/key.pem", @@ -93,7 +93,7 @@ import ssl ctx = ssl.create_default_context() ctx.load_verify_locations(...) -es = Elasticsearch( +client = Elasticsearch( ..., ssl_context=ctx ) @@ -110,7 +110,7 @@ the `Accept-Encoding: gzip` HTTP header. By default compression is disabled. [source,python] ------------------------------------ -es = Elasticsearch( +client = Elasticsearch( ..., http_compress=True # Enable compression! ) @@ -130,13 +130,13 @@ Setting `request_timeout` to `None` will disable timeouts. [source,python] ------------------------------------ -es = Elasticsearch( +client = Elasticsearch( ..., request_timeout=10 # 10 second timeout ) # Search request will timeout in 5 seconds -es.options(request_timeout=5).search(...) +client.options(request_timeout=5).search(...) ------------------------------------ [discrete] @@ -148,7 +148,7 @@ In the example below there are three different configurable timeouts for the `cl [source,python] ------------------------------------ -es.options( +client.options( # Amount of time to wait for an HTTP response to start. request_timeout=30 ).cluster.health( @@ -170,13 +170,13 @@ The maximum number of retries per request can be configured via the `max_retries [source,python] ------------------------------------ -es = Elasticsearch( +client = Elasticsearch( ..., max_retries=5 ) # For this API request we disable retries with 'max_retries=0' -es.options(max_retries=0).index( +client.options(max_retries=0).index( index="blogs", document={ "title": "..." @@ -191,11 +191,11 @@ Connection errors are automatically retried if retries are enabled. Retrying req [source,python] ------------------------------------ -es = Elasticsearch( +client = Elasticsearch( ..., retry_on_timeout=True ) -es.options(retry_on_timeout=False).info() +client.options(retry_on_timeout=False).info() ------------------------------------ [discrete] @@ -205,13 +205,13 @@ By default if retries are enabled `retry_on_status` is set to `(429, 502, 503, 5 [source,python] ------------------------------------ -es = Elasticsearch( +client = Elasticsearch( ..., retry_on_status=() ) # Retry this API on '500 Internal Error' statuses -es.options(retry_on_status=[500]).index( +client.options(retry_on_status=[500]).index( index="blogs", document={ "title": "..." @@ -228,14 +228,14 @@ A good example where this is useful is setting up or cleaning up resources in a [source,python] ------------------------------------ -es = Elasticsearch(...) +client = Elasticsearch(...) # API request is robust against the index not existing: -resp = es.options(ignore_status=404).indices.delete(index="delete-this") +resp = client.options(ignore_status=404).indices.delete(index="delete-this") resp.meta.status # Can be either '2XX' or '404' # API request is robust against the index already existing: -resp = es.options(ignore_status=[400]).indices.create( +resp = client.options(ignore_status=[400]).indices.create( index="create-this", mapping={ "properties": {"field": {"type": "integer"}} @@ -322,7 +322,7 @@ You can specify a node selector pattern via the `node_selector_class` parameter. [source,python] ------------------------------------ -es = Elasticsearch( +client = Elasticsearch( ..., node_selector_class="round_robin" ) @@ -337,7 +337,7 @@ from elastic_transport import NodeSelector class CustomSelector(NodeSelector): def select(nodes): ... -es = Elasticsearch( +client = Elasticsearch( ..., node_selector_class=CustomSelector ) @@ -374,7 +374,7 @@ class JsonSetSerializer(JsonSerializer): return list(data) return super().default(data) -es = Elasticsearch( +client = Elasticsearch( ..., # Serializers are a mapping of 'mimetype' to Serializer class. serializers={"application/json": JsonSetSerializer()} @@ -397,7 +397,7 @@ For all of the built-in HTTP node implementations like `urllib3`, `requests`, an ------------------------------------ from elasticsearch import Elasticsearch -es = Elasticsearch( +client = Elasticsearch( ..., node_class="requests" ) @@ -413,7 +413,7 @@ from elastic_transport import Urllib3HttpNode class CustomHttpNode(Urllib3HttpNode): ... -es = Elasticsearch( +client = Elasticsearch( ... node_class=CustomHttpNode ) @@ -426,7 +426,7 @@ Each node contains its own pool of HTTP connections to allow for concurrent requ [source,python] ------------------------------------ -es = Elasticsearch( +client = Elasticsearch( ..., connections_per_node=5 ) diff --git a/docs/guide/connecting.asciidoc b/docs/guide/connecting.asciidoc index a6f41a97b..101bded51 100644 --- a/docs/guide/connecting.asciidoc +++ b/docs/guide/connecting.asciidoc @@ -251,20 +251,20 @@ or via the per-request `.options()` method: from elasticsearch import Elasticsearch # Authenticate from the constructor -es = Elasticsearch( +client = Elasticsearch( "https://localhost:9200", ca_certs="/path/to/http_ca.crt", basic_auth=("username", "password") ) # Authenticate via the .options() method: -es.options( +client.options( basic_auth=("username", "password") ).indices.get(index="*") # You can persist the authenticated client to use # later or use for multiple API calls: -auth_client = es.options(api_key="api_key") +auth_client = client.options(api_key="api_key") for i in range(10): auth_client.index( index="example-index", @@ -285,7 +285,7 @@ username and password within a tuple: from elasticsearch import Elasticsearch # Adds the HTTP header 'Authorization: Basic ' -es = Elasticsearch( +client = Elasticsearch( "https://localhost:9200", ca_certs="/path/to/http_ca.crt", basic_auth=("username", "password") @@ -307,7 +307,7 @@ and https://www.elastic.co/guide/en/elasticsearch/reference/{branch}/security-ap from elasticsearch import Elasticsearch # Adds the HTTP header 'Authorization: Bearer token-value' -es = Elasticsearch( +client = Elasticsearch( "https://localhost:9200", bearer_auth="token-value" ) @@ -328,7 +328,7 @@ or https://www.elastic.co/guide/en/kibana/current/api-keys.html#create-api-key[K from elasticsearch import Elasticsearch # Adds the HTTP header 'Authorization: ApiKey ' -es = Elasticsearch( +client = Elasticsearch( "https://localhost:9200", ca_certs="/path/to/http_ca.crt", api_key="api_key", diff --git a/docs/guide/examples.asciidoc b/docs/guide/examples.asciidoc index 9b0bb6bc8..b9a5650a6 100644 --- a/docs/guide/examples.asciidoc +++ b/docs/guide/examples.asciidoc @@ -22,14 +22,14 @@ To index a document, you need to specify three pieces of information: `index`, ---------------------------- from datetime import datetime from elasticsearch import Elasticsearch -es = Elasticsearch('https://localhost:9200') +client = Elasticsearch('https://localhost:9200') doc = { 'author': 'author_name', 'text': 'Interesting content...', 'timestamp': datetime.now(), } -resp = es.index(index="test-index", id=1, document=doc) +resp = client.index(index="test-index", id=1, document=doc) print(resp['result']) ---------------------------- @@ -42,7 +42,7 @@ To get a document, you need to specify its `index` and `id`: [source,py] ---------------------------- -resp = es.get(index="test-index", id=1) +resp = client.get(index="test-index", id=1) print(resp['_source']) ---------------------------- @@ -55,7 +55,7 @@ You can perform the refresh operation on an index: [source,py] ---------------------------- -es.indices.refresh(index="test-index") +client.indices.refresh(index="test-index") ---------------------------- @@ -67,7 +67,7 @@ The `search()` method returns results that are matching a query: [source,py] ---------------------------- -resp = es.search(index="test-index", query={"match_all": {}}) +resp = client.search(index="test-index", query={"match_all": {}}) print("Got %d Hits:" % resp['hits']['total']['value']) for hit in resp['hits']['hits']: print("%(timestamp)s %(author)s: %(text)s" % hit["_source"]) diff --git a/docs/guide/integrations.asciidoc b/docs/guide/integrations.asciidoc index 83b88e862..b08446ab0 100644 --- a/docs/guide/integrations.asciidoc +++ b/docs/guide/integrations.asciidoc @@ -23,8 +23,8 @@ The opaque ID can be set via the `opaque_id` parameter via the client `.options( [source,python] ------------------------------------ -es = Elasticsearch(...) -es.options(opaque_id="request-id-...").search(...) +client = Elasticsearch(...) +client.options(opaque_id="request-id-...").search(...) ------------------------------------ @@ -41,8 +41,8 @@ If we write a script that has a type error like using `request_timeout` with a ` # script.py from elasticsearch import Elasticsearch -es = Elasticsearch(...) -es.options( +client = Elasticsearch(...) +client.options( request_timeout="5" # type error! ).search(...) diff --git a/docs/guide/overview.asciidoc b/docs/guide/overview.asciidoc index 916dad833..af7581eb0 100644 --- a/docs/guide/overview.asciidoc +++ b/docs/guide/overview.asciidoc @@ -42,14 +42,14 @@ Simple use-case: >>> from elasticsearch import Elasticsearch # Connect to 'http://localhost:9200' ->>> es = Elasticsearch("http://localhost:9200") +>>> client = Elasticsearch("http://localhost:9200") # Datetimes will be serialized: ->>> es.index(index="my-index-000001", id=42, document={"any": "data", "timestamp": datetime.now()}) +>>> client.index(index="my-index-000001", id=42, document={"any": "data", "timestamp": datetime.now()}) {'_id': '42', '_index': 'my-index-000001', '_type': 'test-type', '_version': 1, 'ok': True} # ...but not deserialized ->>> es.get(index="my-index-000001", id=42)['_source'] +>>> client.get(index="my-index-000001", id=42)['_source'] {'any': 'data', 'timestamp': '2013-05-12T19:45:31.804229'} ------------------------------------ diff --git a/docs/sphinx/async.rst b/docs/sphinx/async.rst index 262d25bae..cb2d72381 100644 --- a/docs/sphinx/async.rst +++ b/docs/sphinx/async.rst @@ -27,10 +27,10 @@ and are used in the same way as other APIs, just with an extra ``await``: import asyncio from elasticsearch import AsyncElasticsearch - es = AsyncElasticsearch() + client = AsyncElasticsearch() async def main(): - resp = await es.search( + resp = await client.search( index="documents", body={"query": {"match_all": {}}}, size=20, @@ -97,20 +97,20 @@ For example if using FastAPI that might look like this: from elasticsearch import AsyncElasticsearch ELASTICSEARCH_URL = os.environ["ELASTICSEARCH_URL"] - es = None + client = None @asynccontextmanager async def lifespan(app: FastAPI): - global es - es = AsyncElasticsearch(ELASTICSEARCH_URL) + global client + client = AsyncElasticsearch(ELASTICSEARCH_URL) yield - await es.close() + await client.close() app = FastAPI(lifespan=lifespan) @app.get("/") async def main(): - return await es.info() + return await client.info() You can run this example by saving it to ``main.py`` and executing ``ELASTICSEARCH_URL=http://localhost:9200 uvicorn main:app``. @@ -140,7 +140,7 @@ Bulk and Streaming Bulk from elasticsearch import AsyncElasticsearch from elasticsearch.helpers import async_bulk - es = AsyncElasticsearch() + client = AsyncElasticsearch() async def gendata(): mywords = ['foo', 'bar', 'baz'] @@ -151,7 +151,7 @@ Bulk and Streaming Bulk } async def main(): - await async_bulk(es, gendata()) + await async_bulk(client, gendata()) loop = asyncio.get_event_loop() loop.run_until_complete(main()) @@ -164,7 +164,7 @@ Bulk and Streaming Bulk from elasticsearch import AsyncElasticsearch from elasticsearch.helpers import async_streaming_bulk - es = AsyncElasticsearch() + client = AsyncElasticsearch() async def gendata(): mywords = ['foo', 'bar', 'baz'] @@ -175,7 +175,7 @@ Bulk and Streaming Bulk } async def main(): - async for ok, result in async_streaming_bulk(es, gendata()): + async for ok, result in async_streaming_bulk(client, gendata()): action, result = result.popitem() if not ok: print("failed to %s document %s" % ()) @@ -194,11 +194,11 @@ Scan from elasticsearch import AsyncElasticsearch from elasticsearch.helpers import async_scan - es = AsyncElasticsearch() + client = AsyncElasticsearch() async def main(): async for doc in async_scan( - client=es, + client=client, query={"query": {"match": {"title": "python"}}}, index="orders-*" ): diff --git a/docs/sphinx/helpers.rst b/docs/sphinx/helpers.rst index cf3c7e213..33b696413 100644 --- a/docs/sphinx/helpers.rst +++ b/docs/sphinx/helpers.rst @@ -74,6 +74,8 @@ document is like ``{"word": ""}``. .. code:: python + from elasticsearch.helpers import bulk + def gendata(): mywords = ['foo', 'bar', 'baz'] for word in mywords: @@ -82,7 +84,7 @@ document is like ``{"word": ""}``. "word": word, } - bulk(es, gendata()) + bulk(client, gendata()) For a more complete and complex example please take a look at diff --git a/docs/sphinx/index.rst b/docs/sphinx/index.rst index bb2d5a86a..70ab257d3 100644 --- a/docs/sphinx/index.rst +++ b/docs/sphinx/index.rst @@ -65,22 +65,22 @@ Example Usage from datetime import datetime from elasticsearch import Elasticsearch - es = Elasticsearch("http://localhost:9200") + client = Elasticsearch("http://localhost:9200/", api_key="YOUR_API_KEY") doc = { "author": "kimchy", "text": "Elasticsearch: cool. bonsai cool.", "timestamp": datetime.now(), } - resp = es.index(index="test-index", id=1, document=doc) + resp = client.index(index="test-index", id=1, document=doc) print(resp["result"]) - resp = es.get(index="test-index", id=1) + resp = client.get(index="test-index", id=1) print(resp["_source"]) - es.indices.refresh(index="test-index") + client.indices.refresh(index="test-index") - resp = es.search(index="test-index", query={"match_all": {}}) + resp = client.search(index="test-index", query={"match_all": {}}) print("Got {} hits:".format(resp["hits"]["total"]["value"])) for hit in resp["hits"]["hits"]: print("{timestamp} {author} {text}".format(**hit["_source"])) diff --git a/elasticsearch/_async/helpers.py b/elasticsearch/_async/helpers.py index f7727993a..1ab55850b 100644 --- a/elasticsearch/_async/helpers.py +++ b/elasticsearch/_async/helpers.py @@ -395,7 +395,7 @@ async def async_scan( .. code-block:: python async_scan( - es, + client, query={"query": {"match": {"title": "python"}}}, index="orders-*" ) diff --git a/elasticsearch/helpers/actions.py b/elasticsearch/helpers/actions.py index 36024e097..e25ea8df6 100644 --- a/elasticsearch/helpers/actions.py +++ b/elasticsearch/helpers/actions.py @@ -656,7 +656,7 @@ def scan( Any additional keyword arguments will be passed to the initial :meth:`~elasticsearch.Elasticsearch.search` call:: - scan(es, + scan(client, query={"query": {"match": {"title": "python"}}}, index="orders-*", doc_type="books" diff --git a/examples/fastapi-apm/app.py b/examples/fastapi-apm/app.py index eccef0103..60a482448 100644 --- a/examples/fastapi-apm/app.py +++ b/examples/fastapi-apm/app.py @@ -15,14 +15,14 @@ apm = make_apm_client( {"SERVICE_NAME": "fastapi-app", "SERVER_URL": "http://apm-server:8200"} ) -es = AsyncElasticsearch(os.environ["ELASTICSEARCH_HOSTS"]) +client = AsyncElasticsearch(os.environ["ELASTICSEARCH_HOSTS"]) app = FastAPI() app.add_middleware(ElasticAPM, client=apm) @app.on_event("shutdown") async def app_shutdown(): - await es.close() + await client.close() async def download_games_db(): @@ -35,16 +35,16 @@ async def download_games_db(): @app.get("/") async def index(): - return await es.cluster.health() + return await client.cluster.health() @app.get("/ingest") async def ingest(): - if not (await es.indices.exists(index="games")): - await es.indices.create(index="games") + if not (await client.indices.exists(index="games")): + await client.indices.create(index="games") async for _ in async_streaming_bulk( - client=es, index="games", actions=download_games_db() + client=client, index="games", actions=download_games_db() ): pass @@ -53,20 +53,20 @@ async def ingest(): @app.get("/search/{query}") async def search(query): - return await es.search( + return await client.search( index="games", body={"query": {"multi_match": {"query": query}}} ) @app.get("/delete") async def delete(): - return await es.delete_by_query(index="games", body={"query": {"match_all": {}}}) + return await client.delete_by_query(index="games", body={"query": {"match_all": {}}}) @app.get("/delete/{id}") async def delete_id(id): try: - return await es.delete(index="games", id=id) + return await client.delete(index="games", id=id) except NotFoundError as e: return e.info, 404 @@ -74,13 +74,13 @@ async def delete_id(id): @app.get("/update") async def update(): response = [] - docs = await es.search( + docs = await client.search( index="games", body={"query": {"multi_match": {"query": ""}}} ) now = datetime.datetime.utcnow() for doc in docs["hits"]["hits"]: response.append( - await es.update( + await client.update( index="games", id=doc["_id"], body={"doc": {"modified": now}} ) ) @@ -91,11 +91,11 @@ async def update(): @app.get("/error") async def error(): try: - await es.delete(index="games", id="somerandomid") + await client.delete(index="games", id="somerandomid") except NotFoundError as e: return e.info @app.get("/doc/{id}") async def get_doc(id): - return await es.get(index="games", id=id) + return await client.get(index="games", id=id)