异步 DSL

文档(Document)

class elasticsearch.dsl.AsyncDocument

用于在elasticsearch中持久化文档的类模型。

__init__(meta=None, **kwargs)
Parameters:
async classmethod bulk(actions, using=None, index=None, validate=True, skip_empty=True, **kwargs)

允许在单个请求中执行多个索引操作。

Parameters:
  • actions (AsyncIterable[Self | Dict[str, Any]]) – 生成要索引的文档实例或批量操作字典的生成器。

  • using (str | AsyncElasticsearch | None) – 要使用的连接别名,默认为 'default'

  • index (str | None) – 要使用的 Elasticsearch 索引,如果 Document 已关联索引则可省略。

  • validate (bool) – 设置为 False 跳过文档验证

  • skip_empty (bool) – 设置为 False 将保留文档上的空值(None, [], {})。否则这些值会被移除, 因为它们在 Elasticsearch 中没有意义。

  • actions

  • using

  • index

  • validate

  • skip_empty

  • kwargs (Any)

Return type:

Tuple[int, int | List[Any]]

所有额外关键字参数将原样传递给 Elasticsearch.bulk

Returns:

批量操作结果

Parameters:
Return type:

Tuple[int, int | List[Any]]

async delete(using=None, index=None, **kwargs)

删除 Elasticsearch 中的实例。

Parameters:
  • index (str | None) – 要使用的 Elasticsearch 索引,如果 Document 已关联索引则可省略。

  • using (str | AsyncElasticsearch | None) – 要使用的连接别名,默认为 'default'

  • using

  • index

  • kwargs (Any)

Return type:

None

所有额外关键字参数将原样传递给 Elasticsearch.delete

async classmethod exists(id, using=None, index=None, **kwargs)

根据文档的 id 检查Elasticsearch中是否存在该文档。

Parameters:
  • id (str) – 要检查存在性的文档 id

  • index (str | None) – 使用的Elasticsearch索引,如果 Document 已关联索引则可省略

  • using (str | AsyncElasticsearch | None) – 使用的连接别名,默认为 'default'

  • id

  • using

  • index

  • kwargs (Any)

Return type:

bool

所有额外的关键字参数将原样传递给 Elasticsearch.exists 方法。

async classmethod get(id, using=None, index=None, **kwargs)

根据文档的 id 从Elasticsearch中检索单个文档。

Parameters:
  • id (str) – 要检索文档的 id

  • index (str | None) – 使用的Elasticsearch索引,如果 Document 已关联索引则可省略

  • using (str | AsyncElasticsearch | None) – 使用的连接别名,默认为 'default'

  • id

  • using

  • index

  • kwargs (Any)

Return type:

Self | None

所有额外的关键字参数将原样传递给 Elasticsearch.get 方法。

async classmethod init(index=None, using=None)

在Elasticsearch中创建索引并填充映射。

Parameters:
Return type:

None

async classmethod mget(docs, using=None, index=None, raise_on_error=True, missing='none', **kwargs)

根据多个文档的 id 批量检索文档。返回的实例列表顺序与请求顺序一致。

Parameters:
Return type:

List[Self | None]

所有额外的关键字参数将原样传递给 Elasticsearch.mget 方法。

async save(using=None, index=None, validate=True, skip_empty=True, return_doc_meta=False, **kwargs)

将文档保存到 Elasticsearch。如果文档不存在则创建, 否则覆盖。如果操作导致新文档创建则返回 True

Parameters:
  • index (str | None) – 要使用的 Elasticsearch 索引,如果 Document 已关联索引则可省略。

  • using (str | AsyncElasticsearch | None) – 要使用的连接别名,默认为 'default'

  • validate (bool) – 设置为 False 跳过文档验证

  • skip_empty (bool) – 设置为 False 将保留文档上的空值(None, [], {})。否则这些值会被移除, 因为它们在 Elasticsearch 中没有意义。

  • return_doc_meta (bool) – 设置为 True 返回更新 API 调用的所有元数据, 而不仅仅是操作结果

  • using

  • index

  • validate

  • skip_empty

  • return_doc_meta

  • kwargs (Any)

Return type:

Any

所有额外关键字参数将原样传递给 Elasticsearch.index

Returns:

操作结果 created/updated

Parameters:
Return type:

Any

classmethod search(using=None, index=None)

创建一个 Search 实例,用于在该 Document 上进行搜索。

Parameters:
Return type:

AsyncSearch[Self]

to_dict(include_meta=False, skip_empty=True)

将实例序列化为字典以便保存到elasticsearch中。

Parameters:
  • include_meta (bool) – 如果设为``True``将包含所有元数据 (_index, ``_id``等)。否则仅序列化文档的 数据。这在将多个实例传递到 ``elasticsearch.helpers.bulk``时很有用。

  • skip_empty (bool) – 如果设为``False``将保留文档中的空值(None, [], ``{}})。否则这些值会被移除,因为它们在elasticsearch中没有区别。

  • include_meta

  • skip_empty

Return type:

Dict[str, Any]

async update(using=None, index=None, detect_noop=True, doc_as_upsert=False, refresh=False, retry_on_conflict=None, script=None, script_id=None, scripted_upsert=False, upsert=None, return_doc_meta=False, **fields)

对文档进行部分更新,指定需要更新的字段, 实例和 Elasticsearch 中的文档都会被更新:

doc = MyDocument(title='Document Title!')
doc.save()
doc.update(title='New Document Title!')
Parameters:
  • index (str | None) – 要使用的 Elasticsearch 索引,如果 Document 已关联索引则可省略。

  • using (str | AsyncElasticsearch | None) – 要使用的连接别名,默认为 'default'

  • detect_noop (bool) – 设置为 False 禁用无操作检测。

  • refresh (bool) – 控制此请求的更改何时对搜索可见。 设置为 True 可立即生效。

  • retry_on_conflict (int | None) – 在更新的获取和索引阶段之间, 可能有其他进程已经更新了同一文档。默认情况下, 更新会因版本冲突异常而失败。retry_on_conflict 参数 控制在最终抛出异常前重试更新的次数。

  • doc_as_upsert (bool) – 设置为 true 时,将使用 doc 内容作为 upsert 值, 而不是发送部分文档加 upsert 文档

  • script (str | Dict[str, Any] | None) – 脚本源代码字符串,或包含要更新脚本属性的字典。

  • return_doc_meta (bool) – 设置为 True 返回索引 API 调用的所有元数据, 而不仅仅是操作结果

  • using

  • index

  • detect_noop

  • doc_as_upsert

  • refresh

  • retry_on_conflict

  • script

  • script_id (str | None)

  • scripted_upsert (bool)

  • upsert (Dict[str, Any] | None)

  • return_doc_meta

  • fields (Any)

Returns:

操作结果 noop/updated

Return type:

Any

索引(Index)

class elasticsearch.dsl.AsyncIndex
__init__(name, using='default')
Parameters:
  • name (str) – 索引名称

  • using (str | AsyncElasticsearch) – 要使用的连接别名,默认为 'default'

  • name

  • using

aliases(**kwargs)

向索引定义添加别名:

i = Index('blog-v2')
i.aliases(blog={}, published={'filter': Q('term', published=True)})
Parameters:

kwargs (Any)

Return type:

Self

async analyze(using=None, **kwargs)

对文本执行分析过程并返回文本的分词结果。

任何额外的关键字参数将原封不动地传递给 Elasticsearch.indices.analyze

Parameters:
Return type:

ObjectApiResponse[Any]

analyzer(*args, **kwargs)

显式地向索引添加一个分析器。注意映射中定义的所有自定义分析器 也会被创建。这对搜索分析器特别有用。

示例:

from elasticsearch.dsl import analyzer, tokenizer

my_analyzer = analyzer('my_analyzer',
    tokenizer=tokenizer('trigram', 'nGram', min_gram=3, max_gram=3),
    filter=['lowercase']
)

i = Index('blog')
i.analyzer(my_analyzer)
Parameters:
Return type:

None

async clear_cache(using=None, **kwargs)

清除所有缓存或与该索引关联的特定缓存。

任何额外的关键字参数将原样传递给 Elasticsearch.indices.clear_cache

Parameters:
Return type:

ObjectApiResponse[Any]

clone(name=None, using=None)

创建具有另一个名称或连接别名的实例副本。 适用于创建具有共享配置的多个索引:

i = Index('base-index')
i.settings(number_of_shards=1)
i.create()

i2 = i.clone('other-index')
i2.create()
Parameters:
  • name (str | None) – 索引名称

  • using (str | AsyncElasticsearch | None) – 要使用的连接别名,默认为 'default'

  • name

  • using

Return type:

Self

async close(using=None, **kwargs)

在elasticsearch中关闭索引。

任何额外的关键字参数将原样传递给 Elasticsearch.indices.close

Parameters:
Return type:

ObjectApiResponse[Any]

async create(using=None, **kwargs)

在 elasticsearch 中创建索引。

任何额外的关键字参数将原样传递给 Elasticsearch.indices.create

Parameters:
Return type:

ObjectApiResponse[Any]

async delete(using=None, **kwargs)

在elasticsearch中删除索引。

任何额外的关键字参数将原样传递给 Elasticsearch.indices.delete

Parameters:
Return type:

ObjectApiResponse[Any]

async delete_alias(using=None, **kwargs)

删除特定别名。

任何额外的关键字参数将原封不动地传递给 Elasticsearch.indices.delete_alias

Parameters:
Return type:

ObjectApiResponse[Any]

document(document)

Document 子类与索引关联。 这意味着当创建此索引时,它将包含该 Document 的映射。如果 Document 类尚未定义默认索引(通过定义 class Index),则将使用此实例。可用作装饰器:

i = Index('blog')

@i.document
class Post(Document):
    title = Text()

# 创建索引,包括 Post 的映射
i.create()

# .search() 现在将返回一个 Search 对象,该对象会返回
# 正确反序列化的 Post 实例
s = i.search()
Parameters:

document (DocumentMeta)

Return type:

DocumentMeta

async exists(using=None, **kwargs)

如果索引已存在于elasticsearch中则返回``True``。

任何额外的关键字参数将原样传递给 Elasticsearch.indices.exists

Parameters:
Return type:

bool

async exists_alias(using=None, **kwargs)

返回布尔值表示该索引是否存在给定别名。

任何额外的关键字参数将原样传递给 Elasticsearch.indices.exists_alias

Parameters:
Return type:

bool

async flush(using=None, **kwargs)

对索引执行刷新写入操作。

任何额外的关键字参数将原封不动地传递给 Elasticsearch.indices.flush

Parameters:
Return type:

ObjectApiResponse[Any]

async forcemerge(using=None, **kwargs)

强制合并API允许通过API强制合并索引。合并涉及Lucene索引在每个分片中 持有的段数量。强制合并操作可以通过合并段来减少其数量。

此调用将阻塞直到合并完成。如果http连接丢失,请求将在后台继续, 任何新的请求都将阻塞直到先前的强制合并完成。

任何额外的关键字参数将原样传递给 Elasticsearch.indices.forcemerge

Parameters:
Return type:

ObjectApiResponse[Any]

async get(using=None, **kwargs)

获取索引API允许检索关于索引的信息。

任何额外的关键字参数将原封不动地传递给 Elasticsearch.indices.get

Parameters:
Return type:

ObjectApiResponse[Any]

async get_alias(using=None, **kwargs)

检索指定的别名。

任何额外的关键字参数将原样传递给 Elasticsearch.indices.get_alias

Parameters:
Return type:

ObjectApiResponse[Any]

async get_field_mapping(using=None, **kwargs)

获取特定字段的映射定义。

任何额外的关键字参数将原样传递给 Elasticsearch.indices.get_field_mapping

Parameters:
Return type:

ObjectApiResponse[Any]

async get_mapping(using=None, **kwargs)

获取特定类型的映射定义。

任何额外的关键字参数将原样传递给 Elasticsearch.indices.get_mapping

Parameters:
Return type:

ObjectApiResponse[Any]

async get_settings(using=None, **kwargs)

检索索引的设置。

任何额外的关键字参数将原封不动地传递给 Elasticsearch.indices.get_settings

Parameters:
Return type:

ObjectApiResponse[Any]

mapping(mapping)

将映射(Mapping 的实例)与此索引关联。 这意味着当创建此索引时,它将包含由这些映射定义的文档类型的映射。

Parameters:

mapping (MappingBase)

Return type:

None

async open(using=None, **kwargs)

在elasticsearch中打开索引。

任何额外的关键字参数将原样传递给 Elasticsearch.indices.open

Parameters:
Return type:

ObjectApiResponse[Any]

async put_alias(using=None, **kwargs)

为索引创建别名。

任何额外的关键字参数将原样传递给 Elasticsearch.indices.put_alias

Parameters:
Return type:

ObjectApiResponse[Any]

async put_mapping(using=None, **kwargs)

为特定类型注册特定的映射定义。

任何额外的关键字参数将原样传递给 Elasticsearch.indices.put_mapping

Parameters:
Return type:

ObjectApiResponse[Any]

async put_settings(using=None, **kwargs)

实时更改特定索引级别的设置。

任何额外的关键字参数将原封不动地传递给 Elasticsearch.indices.put_settings

Parameters:
Return type:

ObjectApiResponse[Any]

async recovery(using=None, **kwargs)

索引恢复API提供对索引正在进行的分片恢复的洞察。

任何额外的关键字参数将原样传递给 Elasticsearch.indices.recovery

Parameters:
Return type:

ObjectApiResponse[Any]

async refresh(using=None, **kwargs)

对索引执行刷新操作。

任何额外的关键字参数将原封不动地传递给 Elasticsearch.indices.refresh

Parameters:
Return type:

ObjectApiResponse[Any]

async save(using=None)

将索引定义与elasticsearch同步,如果索引不存在则创建,如果存在则更新其设置和映射。

注意某些设置和映射更改无法在打开的索引上执行(或根本无法在现有索引上执行), 对于这些情况,此方法将抛出底层异常。

Parameters:

using (str | AsyncElasticsearch | None)

Return type:

Optional[ObjectApiResponse[Any]]

search(using=None)

返回一个 Search 对象,用于搜索该索引 (或属于此模板的所有索引)及其 Documents。

Parameters:

using (str | AsyncElasticsearch | None)

Return type:

AsyncSearch

async segments(using=None, **kwargs)

提供构建Lucene索引(分片级别)的低级段信息。

任何额外的关键字参数将原封不动地传递给 Elasticsearch.indices.segments

Parameters:
Return type:

ObjectApiResponse[Any]

settings(**kwargs)

向索引添加设置:

i = Index('i')
i.settings(number_of_shards=1, number_of_replicas=0)

多次调用 settings 将合并键值,后调用的会覆盖先前的设置。

Parameters:

kwargs (Any)

Return type:

Self

async shard_stores(using=None, **kwargs)

提供索引分片副本的存储信息。存储信息报告了哪些节点存在分片副本、 分片副本版本(指示其新旧程度),以及在打开分片索引时或早期引擎 故障中遇到的任何异常。

任何额外的关键字参数将原样传递给 Elasticsearch.indices.shard_stores

Parameters:
Return type:

ObjectApiResponse[Any]

async shrink(using=None, **kwargs)

shrink index API 允许你将现有索引收缩为一个具有更少主分片的新索引。 目标索引中的主分片数量必须是源索引分片数的因数。例如,一个具有8个主分片的索引 可以收缩为4、2或1个主分片,而具有15个主分片的索引可以收缩为5、3或1个主分片。 如果索引的分片数量是质数,则只能收缩为单个主分片。在收缩之前,索引中每个分片的 (主分片或副本分片)副本必须位于同一节点上。

任何额外的关键字参数将原封不动地传递给 Elasticsearch.indices.shrink

Parameters:
Return type:

ObjectApiResponse[Any]

async stats(using=None, **kwargs)

检索索引上不同操作的统计信息。

任何额外的关键字参数将原封不动地传递给 Elasticsearch.indices.stats

Parameters:
Return type:

ObjectApiResponse[Any]

updateByQuery(using=None)

返回一个 UpdateByQuery 对象,用于搜索该索引 (或属于此模板的所有索引)并更新符合搜索条件的文档。

更多信息请参阅: https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update-by-query.html

Parameters:

using (str | AsyncElasticsearch | None)

Return type:

AsyncUpdateByQuery

async validate_query(using=None, **kwargs)

验证一个可能耗时的查询而不实际执行它。

任何额外的关键字参数将原样传递给 Elasticsearch.indices.validate_query

Parameters:
Return type:

ObjectApiResponse[Any]

映射(Mapping)

class elasticsearch.dsl.AsyncMapping
__init__()
Return type:

None

按查询更新(Update by Query)

class elasticsearch.dsl.AsyncUpdateByQuery
__init__(**kwargs)

向Elasticsearch发送按查询更新请求。

Parameters:
  • using – 使用的`Elasticsearch`实例

  • index – 限定搜索的索引

  • doc_type – 仅查询此类型

  • kwargs (Any)

创建时提供的所有参数(或省略的参数)都可以在后续通过方法覆盖(分别是`using`、index`和`doc_type)。

doc_type(*doc_type, **kwargs)

设置要搜索的文档类型。可以传入单个值或多个值。值可以是字符串或``Document``的子类。

也可以传入任意关键字参数,将文档类型映射到应使用的回调函数而非Hit类。

如果不提供doc_type参数,实例上存储的所有相关信息将被清除。

示例:

s = Search().doc_type(‘product’, ‘store’, User, custom=my_callback)

Parameters:
Return type:

Self

async execute()

执行搜索并返回一个包装所有数据的 Response 实例。

Return type:

UpdateByQueryResponse[_R]

extra(**kwargs)

向请求体添加额外的键。主要用于向后兼容。

Parameters:

kwargs (Any)

Return type:

Self

classmethod from_dict(d)

从包含搜索体的原始字典构造新的`UpdateByQuery`实例。适用于从原始字典迁移的场景。

示例:

ubq = UpdateByQuery.from_dict({
    "query": {
        "bool": {
            "must": [...]
        }
    },
    "script": {...}
})
ubq = ubq.filter('term', published=True)
Parameters:

d (Dict[str, Any])

Return type:

Self

index(*index)

设置搜索的索引。如果调用时不带参数,将移除所有索引信息。

示例:

s = Search()
s = s.index('twitter-2015.01.01', 'twitter-2015.01.02')
s = s.index(['twitter-2015.01.01', 'twitter-2015.01.02'])
Parameters:

index (str | List[str] | Tuple[str, ...])

Return type:

Self

params(**kwargs)

指定执行搜索时使用的查询参数。所有关键字参数将覆盖当前值。 可用参数请参阅 https://elasticsearch-py.readthedocs.io/en/latest/api/elasticsearch.html#elasticsearch.Elasticsearch.search

示例:

s = Search()
s = s.params(routing='user-1', preference='local')
Parameters:

kwargs (Any)

Return type:

Self

response_class(cls)

覆盖响应使用的默认包装器。

Parameters:

cls (Type[UpdateByQueryResponse[_R]])

Return type:

Self

script(**kwargs)

定义要执行的更新操作: 详见https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-scripting-using.html

注意:API只接受单个脚本,因此多次调用script方法会覆盖之前的设置。

示例:

ubq = Search()
ubq = ubq.script(source="ctx._source.likes++"")
ubq = ubq.script(source="ctx._source.likes += params.f"",
             lang="expression",
             params={'f': 3})
Parameters:

kwargs (Any)

Return type:

Self

to_dict(**kwargs)

将搜索序列化为字典,该字典将作为请求体发送。

所有额外的关键字参数都将包含在字典中。

Parameters:

kwargs (Any)

Return type:

Dict[str, Any]

update_from_dict(d)

将序列化体中的选项应用到当前实例。原地修改对象。主要由``from_dict``方法使用。

Parameters:

d (Dict[str, Any])

Return type:

Self

using(client)

将搜索请求与elasticsearch客户端关联。会返回一个新的副本,当前实例保持不变。

Parameters:
  • client (str | Elasticsearch | AsyncElasticsearch) – 要使用的``elasticsearch.Elasticsearch``实例,或 在``elasticsearch.dsl.connections``中查找的别名

  • client

Return type:

Self