Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 73 additions & 0 deletions docs/guide/connecting.asciidoc
Original file line number Diff line number Diff line change
Expand Up @@ -66,3 +66,76 @@ es = Elasticsearch(
api_key=(“api_key_id”, “api_key_secret”)
)
----------------------------

[discrete]
[[connecting-faas]]
=== Using the Client in a Function-as-a-Service Environment

This section illustrates the best practices for leveraging the {es} client in a Function-as-a-Service (FaaS) environment.
The most influential optimization is to initialize the client outside of the function, the global scope.
This practice does not only improve performance but also enables background functionality as – for example –
https://www.elastic.co/blog/elasticsearch-sniffing-best-practices-what-when-why-how[sniffing].
The following examples provide a skeleton for the best practices.

[discrete]
[[connecting-faas-gcp]]
==== GCP Cloud Functions

[source,py]
----------------------------
from elasticsearch import Elasticsearch

client = Elasticsearch(
... # Client initialization
)

def main(request):
... # Use the client

----------------------------

[discrete]
[[connecting-faas-aws]]
==== AWS Lambda

[source,py]
----------------------------
from elasticsearch import Elasticsearch

client = Elasticsearch(
... # Client initialization
)

def main(event, context):
... # Use the client

----------------------------

[discrete]
[[connecting-faas-azure]]
==== Azure Functions

[source,py]
----------------------------
import azure.functions as func
from elasticsearch import Elasticsearch

client = Elasticsearch(
... # Client initialization
)

def main(request: func.HttpRequest) -> func.HttpResponse:
... # Use the client

----------------------------

IMPORTANT: The async client shouldn't be used within Function-as-a-Service as a new event
loop must be started for each invocation. Instead the synchronous `Elasticsearch`
client is recommended.

Resources used to assess these recommendations:

* https://cloud.google.com/functions/docs/bestpractices/tips#use_global_variables_to_reuse_objects_in_future_invocations[GCP Cloud Functions: Tips & Tricks]
* https://docs.aws.amazon.com/lambda/latest/dg/best-practices.html[Best practices for working with AWS Lambda functions]
* https://docs.microsoft.com/en-us/azure/azure-functions/functions-reference-python?tabs=azurecli-linux%2Capplication-level#global-variables[Azure Functions Python developer guide]
* https://docs.aws.amazon.com/lambda/latest/operatorguide/global-scope.html[AWS Lambda: Comparing the effect of global scope]