@@ -66,3 +66,76 @@ es = Elasticsearch(
66
66
api_key=(“api_key_id”, “api_key_secret”)
67
67
)
68
68
----------------------------
69
+
70
+ [discrete]
71
+ [[connecting-faas]]
72
+ === Using the Client in a Function-as-a-Service Environment
73
+
74
+ This section illustrates the best practices for leveraging the {es} client in a Function-as-a-Service (FaaS) environment.
75
+ The most influential optimization is to initialize the client outside of the function, the global scope.
76
+ This practice does not only improve performance but also enables background functionality as – for example –
77
+ https://www.elastic.co/blog/elasticsearch-sniffing-best-practices-what-when-why-how[sniffing].
78
+ The following examples provide a skeleton for the best practices.
79
+
80
+ [discrete]
81
+ [[connecting-faas-gcp]]
82
+ ==== GCP Cloud Functions
83
+
84
+ [source,py]
85
+ ----------------------------
86
+ from elasticsearch import Elasticsearch
87
+
88
+ client = Elasticsearch(
89
+ ... # Client initialization
90
+ )
91
+
92
+ def main(request):
93
+ ... # Use the client
94
+
95
+ ----------------------------
96
+
97
+ [discrete]
98
+ [[connecting-faas-aws]]
99
+ ==== AWS Lambda
100
+
101
+ [source,py]
102
+ ----------------------------
103
+ from elasticsearch import Elasticsearch
104
+
105
+ client = Elasticsearch(
106
+ ... # Client initialization
107
+ )
108
+
109
+ def main(event, context):
110
+ ... # Use the client
111
+
112
+ ----------------------------
113
+
114
+ [discrete]
115
+ [[connecting-faas-azure]]
116
+ ==== Azure Functions
117
+
118
+ [source,py]
119
+ ----------------------------
120
+ import azure.functions as func
121
+ from elasticsearch import Elasticsearch
122
+
123
+ client = Elasticsearch(
124
+ ... # Client initialization
125
+ )
126
+
127
+ def main(request: func.HttpRequest) -> func.HttpResponse:
128
+ ... # Use the client
129
+
130
+ ----------------------------
131
+
132
+ IMPORTANT: The async client shouldn't be used within Function-as-a-Service as a new event
133
+ loop must be started for each invocation. Instead the synchronous `Elasticsearch`
134
+ client is recommended.
135
+
136
+ Resources used to assess these recommendations:
137
+
138
+ * https://cloud.google.com/functions/docs/bestpractices/tips#use_global_variables_to_reuse_objects_in_future_invocations[GCP Cloud Functions: Tips & Tricks]
139
+ * https://docs.aws.amazon.com/lambda/latest/dg/best-practices.html[Best practices for working with AWS Lambda functions]
140
+ * https://docs.microsoft.com/en-us/azure/azure-functions/functions-reference-python?tabs=azurecli-linux%2Capplication-level#global-variables[Azure Functions Python developer guide]
141
+ * https://docs.aws.amazon.com/lambda/latest/operatorguide/global-scope.html[AWS Lambda: Comparing the effect of global scope]
0 commit comments