1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
|
[[connecting]]
== Connecting
This page contains the information you need to connect the Client with {es}.
[discrete]
[[connect-ec]]
=== Connecting to Elastic Cloud
https://www.elastic.co/guide/en/cloud/current/ec-getting-started.html[Elastic Cloud]
is the easiest way to get started with {es}. When connecting to Elastic Cloud
with the Python {es} client you should always use the `cloud_id`
parameter to connect. You can find this value within the "Manage Deployment"
page after you've created a cluster (look in the top-left if you're in Kibana).
We recommend using a Cloud ID whenever possible because your client will be
automatically configured for optimal use with Elastic Cloud including HTTPS and
HTTP compression.
[source,python]
----
from elasticsearch import Elasticsearch
# Password for the 'elastic' user generated by Elasticsearch
ELASTIC_PASSWORD = "<password>"
# Found in the 'Manage Deployment' page
CLOUD_ID = "deployment-name:dXMtZWFzdDQuZ2Nw..."
# Create the client instance
client = Elasticsearch(
cloud_id=CLOUD_ID,
basic_auth=("elastic", ELASTIC_PASSWORD)
)
# Successful response!
client.info()
# {'name': 'instance-0000000000', 'cluster_name': ...}
----
[discrete]
[[connect-self-managed-new]]
=== Connecting to a self-managed cluster
By default {es} will start with security features like authentication and TLS
enabled. To connect to the {es} cluster you'll need to configure the Python {es}
client to use HTTPS with the generated CA certificate in order to make requests
successfully.
If you're just getting started with {es} we recommend reading the documentation
on https://www.elastic.co/guide/en/elasticsearch/reference/current/settings.html[configuring]
and
https://www.elastic.co/guide/en/elasticsearch/reference/current/starting-elasticsearch.html[starting {es}]
to ensure your cluster is running as expected.
When you start {es} for the first time you'll see a distinct block like the one
below in the output from {es} (you may have to scroll up if it's been a while):
```sh
----------------------------------------------------------------
-> Elasticsearch security features have been automatically configured!
-> Authentication is enabled and cluster connections are encrypted.
-> Password for the elastic user (reset with `bin/elasticsearch-reset-password -u elastic`):
lhQpLELkjkrawaBoaz0Q
-> HTTP CA certificate SHA-256 fingerprint:
a52dd93511e8c6045e21f16654b77c9ee0f34aea26d9f40320b531c474676228
...
----------------------------------------------------------------
```
Note down the `elastic` user password and HTTP CA fingerprint for the next
sections. In the examples below they will be stored in the variables
`ELASTIC_PASSWORD` and `CERT_FINGERPRINT` respectively.
Depending on the circumstances there are two options for verifying the HTTPS
connection, either verifying with the CA certificate itself or via the HTTP CA
certificate fingerprint.
[discrete]
==== Verifying HTTPS with CA certificates
Using the `ca_certs` option is the default way the Python {es} client verifies
an HTTPS connection.
The generated root CA certificate can be found in the `certs` directory in your
{es} config location (`$ES_CONF_PATH/certs/http_ca.crt`). If you're running {es}
in Docker there is
https://www.elastic.co/guide/en/elasticsearch/reference/current/docker.html[additional documentation for retrieving the CA certificate].
Once you have the `http_ca.crt` file somewhere accessible pass the path to the
client via `ca_certs`:
[source,python]
----
from elasticsearch import Elasticsearch
# Password for the 'elastic' user generated by Elasticsearch
ELASTIC_PASSWORD = "<password>"
# Create the client instance
client = Elasticsearch(
"https://localhost:9200",
ca_certs="/path/to/http_ca.crt",
basic_auth=("elastic", ELASTIC_PASSWORD)
)
# Successful response!
client.info()
# {'name': 'instance-0000000000', 'cluster_name': ...}
----
NOTE: If you don't specify `ca_certs` or `ssl_assert_fingerprint` then the
https://certifiio.readthedocs.io[certifi package] will be used for `ca_certs` by
default if available.
[discrete]
==== Verifying HTTPS with certificate fingerprints (Python 3.10 or later)
NOTE: Using this method **requires using Python 3.10 or later** and isn't
available when using the `aiohttp` HTTP client library so can't be used with
`AsyncElasticsearch`.
This method of verifying the HTTPS connection takes advantage of the certificate
fingerprint value noted down earlier. Take this SHA256 fingerprint value and
pass it to the Python {es} client via `ssl_assert_fingerprint`:
[source,python]
----
from elasticsearch import Elasticsearch
# Fingerprint either from Elasticsearch startup or above script.
# Colons and uppercase/lowercase don't matter when using
# the 'ssl_assert_fingerprint' parameter
CERT_FINGERPRINT = "A5:2D:D9:35:11:E8:C6:04:5E:21:F1:66:54:B7:7C:9E:E0:F3:4A:EA:26:D9:F4:03:20:B5:31:C4:74:67:62:28"
# Password for the 'elastic' user generated by Elasticsearch
ELASTIC_PASSWORD = "<password>"
client = Elasticsearch(
"https://localhost:9200",
ssl_assert_fingerprint=CERT_FINGERPRINT,
basic_auth=("elastic", ELASTIC_PASSWORD)
)
# Successful response!
client.info()
# {'name': 'instance-0000000000', 'cluster_name': ...}
----
The certificate fingerprint can be calculated using `openssl x509` with the
certificate file:
[source,sh]
----
openssl x509 -fingerprint -sha256 -noout -in /path/to/http_ca.crt
----
If you don't have access to the generated CA file from {es} you can use the
following script to output the root CA fingerprint of the {es} instance with
`openssl s_client`:
[source,sh]
----
# Replace the values of 'localhost' and '9200' to the
# corresponding host and port values for the cluster.
openssl s_client -connect localhost:9200 -servername localhost -showcerts </dev/null 2>/dev/null \
| openssl x509 -fingerprint -sha256 -noout -in /dev/stdin
----
The output of `openssl x509` will look something like this:
[source,sh]
----
SHA256 Fingerprint=A5:2D:D9:35:11:E8:C6:04:5E:21:F1:66:54:B7:7C:9E:E0:F3:4A:EA:26:D9:F4:03:20:B5:31:C4:74:67:62:28
----
[discrete]
[[connect-no-security]]
=== Connecting without security enabled
WARNING: Running {es} without security enabled is not recommended.
If your cluster is configured with
https://www.elastic.co/guide/en/elasticsearch/reference/current/security-settings.html[security explicitly disabled]
then you can connect via HTTP:
[source,python]
----
from elasticsearch import Elasticsearch
# Create the client instance
client = Elasticsearch("http://localhost:9200")
# Successful response!
client.info()
# {'name': 'instance-0000000000', 'cluster_name': ...}
----
[discrete]
[[connect-url]]
=== Connecting to multiple nodes
The Python {es} client supports sending API requests to multiple nodes in the
cluster. This means that work will be more evenly spread across the cluster
instead of hammering the same node over and over with requests. To configure the
client with multiple nodes you can pass a list of URLs, each URL will be used as
a separate node in the pool.
[source,python]
----
from elasticsearch import Elasticsearch
# List of nodes to connect use with different hosts and ports.
NODES = [
"https://localhost:9200",
"https://localhost:9201",
"https://localhost:9202",
]
# Password for the 'elastic' user generated by Elasticsearch
ELASTIC_PASSWORD = "<password>"
client = Elasticsearch(
NODES,
ca_certs="/path/to/http_ca.crt",
basic_auth=("elastic", ELASTIC_PASSWORD)
)
----
By default nodes are selected using round-robin, but alternate node selection
strategies can be configured with `node_selector_class` parameter.
NOTE: If your {es} cluster is behind a load balancer like when using Elastic
Cloud you won't need to configure multiple nodes. Instead use the load balancer
host and port.
[discrete]
[[authentication]]
=== Authentication
This section contains code snippets to show you how to connect to various {es}
providers. All authentication methods are supported on the client constructor
or via the per-request `.options()` method:
[source,python]
----
from elasticsearch import Elasticsearch
# Authenticate from the constructor
client = Elasticsearch(
"https://localhost:9200",
ca_certs="/path/to/http_ca.crt",
basic_auth=("username", "password")
)
# Authenticate via the .options() method:
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 = client.options(api_key="api_key")
for i in range(10):
auth_client.index(
index="example-index",
document={"field": i}
)
----
[discrete]
[[auth-basic]]
==== HTTP Basic authentication (Username and Password)
HTTP Basic authentication uses the `basic_auth` parameter by passing in a
username and password within a tuple:
[source,python]
----
from elasticsearch import Elasticsearch
# Adds the HTTP header 'Authorization: Basic <base64 username:password>'
client = Elasticsearch(
"https://localhost:9200",
ca_certs="/path/to/http_ca.crt",
basic_auth=("username", "password")
)
----
[discrete]
[[auth-bearer]]
==== HTTP Bearer authentication
HTTP Bearer authentication uses the `bearer_auth` parameter by passing the token
as a string. This authentication method is used by
https://www.elastic.co/guide/en/elasticsearch/reference/{branch}/security-api-create-service-token.html[Service Account Tokens]
and https://www.elastic.co/guide/en/elasticsearch/reference/{branch}/security-api-get-token.html[Bearer Tokens].
[source,python]
----
from elasticsearch import Elasticsearch
# Adds the HTTP header 'Authorization: Bearer token-value'
client = Elasticsearch(
"https://localhost:9200",
bearer_auth="token-value"
)
----
[discrete]
[[auth-apikey]]
==== API Key authentication
You can configure the client to use {es}'s API Key for connecting to your
cluster. These can be generated through the
https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-create-api-key.html[Elasticsearch Create API key API]
or https://www.elastic.co/guide/en/kibana/current/api-keys.html#create-api-key[Kibana Stack Management].
[source,python]
----
from elasticsearch import Elasticsearch
# Adds the HTTP header 'Authorization: ApiKey <base64 api_key.id:api_key.api_key>'
client = Elasticsearch(
"https://localhost:9200",
ca_certs="/path/to/http_ca.crt",
api_key="api_key",
)
----
[discrete]
[[compatibility-mode]]
=== Enabling the Compatibility Mode
The {es} server version 8.0 is introducing a new compatibility mode that allows
you a smoother upgrade experience from 7 to 8. In a nutshell, you can use the
latest 7.x Python {es} {es} client with an 8.x {es} server, giving more room to
coordinate the upgrade of your codebase to the next major version.
If you want to leverage this functionality, please make sure that you are using
the latest 7.x Python {es} client and set the environment variable
`ELASTIC_CLIENT_APIVERSIONING` to `true`. The client is handling the rest
internally. For every 8.0 and beyond Python {es} client, you're all set! The
compatibility mode is enabled by default.
[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.
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.
[discrete]
[[connecting-faas-gcp]]
==== GCP Cloud Functions
[source,python]
----
from elasticsearch import Elasticsearch
# Client initialization
client = Elasticsearch(
cloud_id="deployment-name:ABCD...",
api_key=...
)
def main(request):
# Use the client
client.search(index=..., query={"match_all": {}})
----
[discrete]
[[connecting-faas-aws]]
==== AWS Lambda
[source,python]
----
from elasticsearch import Elasticsearch
# Client initialization
client = Elasticsearch(
cloud_id="deployment-name:ABCD...",
api_key=...
)
def main(event, context):
# Use the client
client.search(index=..., query={"match_all": {}})
----
[discrete]
[[connecting-faas-azure]]
==== Azure Functions
[source,python]
----
import azure.functions as func
from elasticsearch import Elasticsearch
# Client initialization
client = Elasticsearch(
cloud_id="deployment-name:ABCD...",
api_key=...
)
def main(request: func.HttpRequest) -> func.HttpResponse:
# Use the client
client.search(index=..., query={"match_all": {}})
----
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]
|