Python client for Elasticsearch with comprehensive API coverage and both sync and async support
—
Comprehensive index lifecycle operations including creation, deletion, mapping updates, settings configuration, and maintenance operations. These operations manage the structure and configuration of Elasticsearch indices.
Create new indices with mappings, settings, and aliases.
def create(
self,
index: str,
mappings: Optional[Dict[str, Any]] = None,
settings: Optional[Dict[str, Any]] = None,
aliases: Optional[Dict[str, Any]] = None,
timeout: Optional[str] = None,
master_timeout: Optional[str] = None,
wait_for_active_shards: Optional[str] = None,
**kwargs
) -> ObjectApiResponse:
"""
Create an index.
Parameters:
- index: Index name to create
- mappings: Field mappings for the index
- settings: Index settings configuration
- aliases: Index aliases to create
- timeout: Request timeout
- master_timeout: Timeout for master node response
- wait_for_active_shards: Wait for active shard count
Returns:
ObjectApiResponse with creation result
"""Delete indices with support for multiple indices and wildcard patterns.
def delete(
self,
index: Union[str, List[str]],
timeout: Optional[str] = None,
master_timeout: Optional[str] = None,
ignore_unavailable: Optional[bool] = None,
allow_no_indices: Optional[bool] = None,
expand_wildcards: Optional[str] = None,
**kwargs
) -> ObjectApiResponse:
"""
Delete one or more indices.
Parameters:
- index: Index name(s) to delete
- timeout: Request timeout
- master_timeout: Timeout for master node response
- ignore_unavailable: Whether to ignore unavailable indices
- allow_no_indices: Whether empty index list is acceptable
- expand_wildcards: How to expand wildcard patterns
Returns:
ObjectApiResponse with deletion result
"""Retrieve comprehensive information about indices including mappings, settings, and aliases.
def get(
self,
index: Union[str, List[str]],
allow_no_indices: Optional[bool] = None,
expand_wildcards: Optional[str] = None,
flat_settings: Optional[bool] = None,
ignore_unavailable: Optional[bool] = None,
include_defaults: Optional[bool] = None,
local: Optional[bool] = None,
master_timeout: Optional[str] = None,
**kwargs
) -> ObjectApiResponse:
"""
Get index information.
Parameters:
- index: Index name(s) to get information for
- allow_no_indices: Whether empty index list is acceptable
- expand_wildcards: How to expand wildcard patterns
- flat_settings: Whether to return settings in flat format
- ignore_unavailable: Whether to ignore unavailable indices
- include_defaults: Whether to include default settings
- local: Whether to return local information only
- master_timeout: Timeout for master node response
Returns:
ObjectApiResponse with index information
"""Update and retrieve field mappings for indices.
def put_mapping(
self,
index: Union[str, List[str]],
properties: Optional[Dict[str, Any]] = None,
_meta: Optional[Dict[str, Any]] = None,
_source: Optional[Dict[str, Any]] = None,
dynamic: Optional[Union[bool, str]] = None,
dynamic_templates: Optional[List[Dict[str, Any]]] = None,
runtime: Optional[Dict[str, Any]] = None,
timeout: Optional[str] = None,
master_timeout: Optional[str] = None,
ignore_unavailable: Optional[bool] = None,
allow_no_indices: Optional[bool] = None,
expand_wildcards: Optional[str] = None,
write_index_only: Optional[bool] = None,
**kwargs
) -> ObjectApiResponse:
"""
Update index mappings.
Parameters:
- index: Index name(s) to update mappings for
- properties: Field mapping definitions
- _meta: Metadata for the mapping
- _source: Source field configuration
- dynamic: Dynamic mapping behavior
- dynamic_templates: Dynamic mapping templates
- runtime: Runtime field definitions
- timeout: Request timeout
- master_timeout: Timeout for master node response
- ignore_unavailable: Whether to ignore unavailable indices
- allow_no_indices: Whether empty index list is acceptable
- expand_wildcards: How to expand wildcard patterns
- write_index_only: Whether to apply only to write index
Returns:
ObjectApiResponse with mapping update result
"""
def get_mapping(
self,
index: Optional[Union[str, List[str]]] = None,
ignore_unavailable: Optional[bool] = None,
allow_no_indices: Optional[bool] = None,
expand_wildcards: Optional[str] = None,
master_timeout: Optional[str] = None,
local: Optional[bool] = None,
**kwargs
) -> ObjectApiResponse:
"""
Get index mappings.
Parameters:
- index: Index name(s) to get mappings for
- ignore_unavailable: Whether to ignore unavailable indices
- allow_no_indices: Whether empty index list is acceptable
- expand_wildcards: How to expand wildcard patterns
- master_timeout: Timeout for master node response
- local: Whether to return local information only
Returns:
ObjectApiResponse with index mappings
"""Configure and retrieve index settings.
def put_settings(
self,
index: Union[str, List[str]],
settings: Dict[str, Any],
timeout: Optional[str] = None,
master_timeout: Optional[str] = None,
preserve_existing: Optional[bool] = None,
ignore_unavailable: Optional[bool] = None,
allow_no_indices: Optional[bool] = None,
expand_wildcards: Optional[str] = None,
flat_settings: Optional[bool] = None,
**kwargs
) -> ObjectApiResponse:
"""
Update index settings.
Parameters:
- index: Index name(s) to update settings for
- settings: Settings to update
- timeout: Request timeout
- master_timeout: Timeout for master node response
- preserve_existing: Whether to preserve existing settings
- ignore_unavailable: Whether to ignore unavailable indices
- allow_no_indices: Whether empty index list is acceptable
- expand_wildcards: How to expand wildcard patterns
- flat_settings: Whether settings are in flat format
Returns:
ObjectApiResponse with settings update result
"""
def get_settings(
self,
index: Optional[Union[str, List[str]]] = None,
name: Optional[Union[str, List[str]]] = None,
ignore_unavailable: Optional[bool] = None,
allow_no_indices: Optional[bool] = None,
expand_wildcards: Optional[str] = None,
flat_settings: Optional[bool] = None,
local: Optional[bool] = None,
master_timeout: Optional[str] = None,
include_defaults: Optional[bool] = None,
**kwargs
) -> ObjectApiResponse:
"""
Get index settings.
Parameters:
- index: Index name(s) to get settings for
- name: Setting name(s) to retrieve
- ignore_unavailable: Whether to ignore unavailable indices
- allow_no_indices: Whether empty index list is acceptable
- expand_wildcards: How to expand wildcard patterns
- flat_settings: Whether to return settings in flat format
- local: Whether to return local information only
- master_timeout: Timeout for master node response
- include_defaults: Whether to include default settings
Returns:
ObjectApiResponse with index settings
"""Control index status and perform maintenance operations.
def open(
self,
index: Union[str, List[str]],
timeout: Optional[str] = None,
master_timeout: Optional[str] = None,
ignore_unavailable: Optional[bool] = None,
allow_no_indices: Optional[bool] = None,
expand_wildcards: Optional[str] = None,
wait_for_active_shards: Optional[str] = None,
**kwargs
) -> ObjectApiResponse:
"""
Open closed indices.
Parameters:
- index: Index name(s) to open
- timeout: Request timeout
- master_timeout: Timeout for master node response
- ignore_unavailable: Whether to ignore unavailable indices
- allow_no_indices: Whether empty index list is acceptable
- expand_wildcards: How to expand wildcard patterns
- wait_for_active_shards: Wait for active shard count
Returns:
ObjectApiResponse with open result
"""
def close(
self,
index: Union[str, List[str]],
timeout: Optional[str] = None,
master_timeout: Optional[str] = None,
ignore_unavailable: Optional[bool] = None,
allow_no_indices: Optional[bool] = None,
expand_wildcards: Optional[str] = None,
wait_for_active_shards: Optional[str] = None,
**kwargs
) -> ObjectApiResponse:
"""
Close indices.
Parameters:
- index: Index name(s) to close
- timeout: Request timeout
- master_timeout: Timeout for master node response
- ignore_unavailable: Whether to ignore unavailable indices
- allow_no_indices: Whether empty index list is acceptable
- expand_wildcards: How to expand wildcard patterns
- wait_for_active_shards: Wait for active shard count
Returns:
ObjectApiResponse with close result
"""Perform maintenance operations on indices.
def refresh(
self,
index: Optional[Union[str, List[str]]] = None,
ignore_unavailable: Optional[bool] = None,
allow_no_indices: Optional[bool] = None,
expand_wildcards: Optional[str] = None,
**kwargs
) -> ObjectApiResponse:
"""
Refresh indices to make recent changes searchable.
Parameters:
- index: Index name(s) to refresh
- ignore_unavailable: Whether to ignore unavailable indices
- allow_no_indices: Whether empty index list is acceptable
- expand_wildcards: How to expand wildcard patterns
Returns:
ObjectApiResponse with refresh result
"""
def flush(
self,
index: Optional[Union[str, List[str]]] = None,
force: Optional[bool] = None,
wait_if_ongoing: Optional[bool] = None,
ignore_unavailable: Optional[bool] = None,
allow_no_indices: Optional[bool] = None,
expand_wildcards: Optional[str] = None,
**kwargs
) -> ObjectApiResponse:
"""
Flush indices to ensure data is written to disk.
Parameters:
- index: Index name(s) to flush
- force: Whether to force flush even if not necessary
- wait_if_ongoing: Whether to wait if flush is ongoing
- ignore_unavailable: Whether to ignore unavailable indices
- allow_no_indices: Whether empty index list is acceptable
- expand_wildcards: How to expand wildcard patterns
Returns:
ObjectApiResponse with flush result
"""
def force_merge(
self,
index: Optional[Union[str, List[str]]] = None,
max_num_segments: Optional[int] = None,
only_expunge_deletes: Optional[bool] = None,
flush: Optional[bool] = None,
ignore_unavailable: Optional[bool] = None,
allow_no_indices: Optional[bool] = None,
expand_wildcards: Optional[str] = None,
wait_for_completion: Optional[bool] = None,
**kwargs
) -> ObjectApiResponse:
"""
Force merge index segments.
Parameters:
- index: Index name(s) to force merge
- max_num_segments: Maximum number of segments to merge to
- only_expunge_deletes: Whether to only expunge deleted documents
- flush: Whether to flush after merge
- ignore_unavailable: Whether to ignore unavailable indices
- allow_no_indices: Whether empty index list is acceptable
- expand_wildcards: How to expand wildcard patterns
- wait_for_completion: Whether to wait for completion
Returns:
ObjectApiResponse with force merge result
"""Retrieve detailed statistics about indices.
def stats(
self,
index: Optional[Union[str, List[str]]] = None,
metric: Optional[Union[str, List[str]]] = None,
completion_fields: Optional[Union[str, List[str]]] = None,
fielddata_fields: Optional[Union[str, List[str]]] = None,
fields: Optional[Union[str, List[str]]] = None,
groups: Optional[Union[str, List[str]]] = None,
level: Optional[str] = None,
types: Optional[Union[str, List[str]]] = None,
include_segment_file_sizes: Optional[bool] = None,
include_unloaded_segments: Optional[bool] = None,
expand_wildcards: Optional[str] = None,
**kwargs
) -> ObjectApiResponse:
"""
Get index statistics.
Parameters:
- index: Index name(s) to get statistics for
- metric: Specific metrics to return
- completion_fields: Completion fields to include
- fielddata_fields: Fielddata fields to include
- fields: Fields to include in statistics
- groups: Statistics groups to include
- level: Level of detail (cluster, indices, shards)
- types: Document types to include
- include_segment_file_sizes: Whether to include segment file sizes
- include_unloaded_segments: Whether to include unloaded segments
- expand_wildcards: How to expand wildcard patterns
Returns:
ObjectApiResponse with index statistics
"""Manage index aliases for flexible index organization.
def put_alias(
self,
index: Union[str, List[str]],
name: str,
filter: Optional[Dict[str, Any]] = None,
routing: Optional[str] = None,
index_routing: Optional[str] = None,
search_routing: Optional[str] = None,
is_write_index: Optional[bool] = None,
timeout: Optional[str] = None,
master_timeout: Optional[str] = None,
**kwargs
) -> ObjectApiResponse:
"""
Create or update an index alias.
Parameters:
- index: Index name(s) for the alias
- name: Alias name
- filter: Filter query for the alias
- routing: Routing value for the alias
- index_routing: Routing for index operations
- search_routing: Routing for search operations
- is_write_index: Whether this is the write index for the alias
- timeout: Request timeout
- master_timeout: Timeout for master node response
Returns:
ObjectApiResponse with alias creation result
"""
def get_alias(
self,
index: Optional[Union[str, List[str]]] = None,
name: Optional[Union[str, List[str]]] = None,
ignore_unavailable: Optional[bool] = None,
allow_no_indices: Optional[bool] = None,
expand_wildcards: Optional[str] = None,
local: Optional[bool] = None,
**kwargs
) -> ObjectApiResponse:
"""
Get index aliases.
Parameters:
- index: Index name(s) to get aliases for
- name: Alias name(s) to retrieve
- ignore_unavailable: Whether to ignore unavailable indices
- allow_no_indices: Whether empty index list is acceptable
- expand_wildcards: How to expand wildcard patterns
- local: Whether to return local information only
Returns:
ObjectApiResponse with alias information
"""
def delete_alias(
self,
index: Union[str, List[str]],
name: Union[str, List[str]],
timeout: Optional[str] = None,
master_timeout: Optional[str] = None,
**kwargs
) -> ObjectApiResponse:
"""
Delete index aliases.
Parameters:
- index: Index name(s) to delete aliases from
- name: Alias name(s) to delete
- timeout: Request timeout
- master_timeout: Timeout for master node response
Returns:
ObjectApiResponse with deletion result
"""from elasticsearch import Elasticsearch
client = Elasticsearch(hosts=['http://localhost:9200'])
# Create index with mappings and settings
client.indices.create(
index="products",
mappings={
"properties": {
"name": {"type": "text", "analyzer": "standard"},
"description": {"type": "text"},
"price": {"type": "double"},
"category": {"type": "keyword"},
"created_at": {"type": "date"},
"tags": {"type": "keyword"},
"location": {"type": "geo_point"}
}
},
settings={
"number_of_shards": 2,
"number_of_replicas": 1,
"analysis": {
"analyzer": {
"custom_analyzer": {
"type": "custom",
"tokenizer": "standard",
"filter": ["lowercase", "asciifolding"]
}
}
}
}
)
# Add an alias
client.indices.put_alias(
index="products",
name="current_products",
filter={"term": {"status": "active"}}
)
# Update mapping to add new field
client.indices.put_mapping(
index="products",
properties={
"rating": {"type": "float"},
"review_count": {"type": "integer"}
}
)
# Update settings
client.indices.put_settings(
index="products",
settings={
"index.refresh_interval": "30s",
"index.max_result_window": 20000
}
)
# Get index information
info = client.indices.get(index="products")
print(f"Index settings: {info.body['products']['settings']}")
print(f"Index mappings: {info.body['products']['mappings']}")
# Perform maintenance
client.indices.refresh(index="products")
client.indices.flush(index="products")
# Get statistics
stats = client.indices.stats(index="products")
print(f"Document count: {stats.body['indices']['products']['total']['docs']['count']}")
print(f"Store size: {stats.body['indices']['products']['total']['store']['size_in_bytes']}")# Create an index template
client.indices.put_index_template(
name="logs_template",
index_patterns=["logs-*"],
template={
"settings": {
"number_of_shards": 1,
"number_of_replicas": 0,
"index.lifecycle.name": "logs_policy"
},
"mappings": {
"properties": {
"@timestamp": {"type": "date"},
"level": {"type": "keyword"},
"message": {"type": "text"},
"host": {"type": "keyword"},
"service": {"type": "keyword"}
}
}
},
priority=100
)
# Indices created with matching patterns will use this template
client.index(
index="logs-2024-01-01",
document={
"@timestamp": "2024-01-01T10:00:00Z",
"level": "INFO",
"message": "Application started",
"host": "web-01",
"service": "api"
}
)Install with Tessl CLI
npx tessl i tessl/pypi-elasticsearch