A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://elasticsearch-py.readthedocs.io/en/latest/async_dsl.html below:

Website Navigation


Async DSL — Python Elasticsearch client 9.1.0 documentation

Async DSL Search
class elasticsearch.dsl.AsyncSearch
__init__(using='default', index=None, **kwargs)

Search request to elasticsearch.

Parameters:

All the parameters supplied (or omitted) at creation type can be later overridden by methods (using, index and doc_type respectively).

collapse(field=None, inner_hits=None, max_concurrent_group_searches=None)

Add collapsing information to the search request. If called without providing field, it will remove all collapse requirements, otherwise it will replace them with the provided arguments. The API returns a copy of the Search object and can thus be chained.

Parameters:
  • field (str | InstrumentedField | None)

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

  • max_concurrent_group_searches (int | None)

Return type:

Self

async count()

Return the number of hits matching the query and filters. Note that only the actual number is returned.

Return type:

int

async delete()

delete() executes the query by delegating to delete_by_query().

Use the params method to specify any additional arguments you wish to pass to the underlying delete_by_query helper from elasticsearch-py - https://elasticsearch-py.readthedocs.io/en/latest/api/elasticsearch.html#elasticsearch.Elasticsearch.delete_by_query

Return type:

AttrDict[Any]

doc_type(*doc_type, **kwargs)

Set the type to search through. You can supply a single value or multiple. Values can be strings or subclasses of Document.

You can also pass in any keyword arguments, mapping a doc_type to a callback that should be used instead of the Hit class.

If no doc_type is supplied any information stored on the instance will be erased.

Example:

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

Parameters:
Return type:

Self

exclude(*args, **kwargs)

Add a negative query in filter context.

Parameters:
Return type:

Self

async execute(ignore_cache=False)

Execute the search and return an instance of Response wrapping all the data.

Parameters:
  • ignore_cache (bool) – if set to True, consecutive calls will hit ES, while cached result will be ignored. Defaults to False

  • ignore_cache

Return type:

Response[_R]

Add extra keys to the request body. Mostly here for backwards compatibility.

Parameters:

kwargs (Any)

Return type:

Self

filter(*args, **kwargs)

Add a query in filter context.

Parameters:
Return type:

Self

classmethod from_dict(d)

Construct a new Search instance from a raw dict containing the search body. Useful when migrating from raw dictionaries.

Example:

s = Search.from_dict({
    "query": {
        "bool": {
            "must": [...]
        }
    },
    "aggs": {...}
})
s = s.filter('term', published=True)
Parameters:

d (Dict[str, Any])

Return type:

Self

highlight(*fields, **kwargs)

Request highlighting of some fields. All keyword arguments passed in will be used as parameters for all the fields in the fields parameter. Example:

Search().highlight('title', 'body', fragment_size=50)

will produce the equivalent of:

{
    "highlight": {
        "fields": {
            "body": {"fragment_size": 50},
            "title": {"fragment_size": 50}
        }
    }
}

If you want to have different options for different fields you can call highlight twice:

Search().highlight('title', fragment_size=50).highlight('body', fragment_size=100)

which will produce:

{
    "highlight": {
        "fields": {
            "body": {"fragment_size": 100},
            "title": {"fragment_size": 50}
        }
    }
}
Parameters:
  • fields (str | InstrumentedField)

  • kwargs (Any)

Return type:

Self

highlight_options(**kwargs)

Update the global highlighting options used for this request. For example:

s = Search()
s = s.highlight_options(order='score')
Parameters:

kwargs (Any)

Return type:

Self

index(*index)

Set the index for the search. If called empty it will remove all information.

Example:

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

async iterate(keep_alive='1m')

Return a generator that iterates over all the documents matching the query.

This method uses a point in time to provide consistent results even when the index is changing. It should be preferred over scan().

Parameters:
  • keep_alive (str) – the time to live for the point in time, renewed with each new search request

  • keep_alive

Return type:

AsyncIterator[_R]

knn(field, k, num_candidates, query_vector=None, query_vector_builder=None, boost=None, filter=None, similarity=None, inner_hits=None)

Add a k-nearest neighbor (kNN) search.

Parameters:
  • field (str | InstrumentedField) – the vector field to search against as a string or document class attribute

  • k (int) – number of nearest neighbors to return as top hits

  • num_candidates (int) – number of nearest neighbor candidates to consider per shard

  • query_vector (List[float] | None) – the vector to search for

  • query_vector_builder (Dict[str, Any] | None) – A dictionary indicating how to build a query vector

  • boost (float | None) – A floating-point boost factor for kNN scores

  • filter (Query | None) – query to filter the documents that can match

  • similarity (float | None) – the minimum similarity required for a document to be considered a match, as a float value

  • inner_hits (Dict[str, Any] | None) – retrieve hits from nested field

  • field

  • k

  • num_candidates

  • query_vector

  • query_vector_builder

  • boost

  • filter

  • similarity

  • inner_hits

Return type:

Self

Example:

s = Search()
s = s.knn(field='embedding', k=5, num_candidates=10, query_vector=vector,
          filter=Q('term', category='blog')))
params(**kwargs)

Specify query params to be used when executing the search. All the keyword arguments will override the current values. See https://elasticsearch-py.readthedocs.io/en/latest/api/elasticsearch.html#elasticsearch.Elasticsearch.search for all available parameters.

Example:

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

kwargs (Any)

Return type:

Self

point_in_time(keep_alive='1m')

Open a point in time (pit) that can be used across several searches.

This method implements a context manager that returns a search object configured to operate within the created pit.

Parameters:
  • keep_alive (str) – the time to live for the point in time, renewed with each search request

  • keep_alive

Return type:

AsyncIterator[Self]

rank(rrf=None)

Defines a method for combining and ranking results sets from a combination of searches. Requires a minimum of 2 results sets.

Parameters:
  • rrf (bool | Dict[str, Any] | None) – Set to True or an options dictionary to set the rank method to reciprocal rank fusion (RRF).

  • rrf

Return type:

Self

Example:

s = Search()
s = s.query('match', content='search text')
s = s.knn(field='embedding', k=5, num_candidates=10, query_vector=vector)
s = s.rank(rrf=True)

Note: This option is in technical preview and may change in the future. The syntax will likely change before GA.

response_class(cls)

Override the default wrapper used for the response.

Parameters:

cls (Type[Response[_R]])

Return type:

Self

async scan()

Turn the search into a scan search and return a generator that will iterate over all the documents matching the query.

Use the params method to specify any additional arguments you wish to pass to the underlying scan helper from elasticsearch-py - https://elasticsearch-py.readthedocs.io/en/latest/helpers.html#scan

The iterate() method should be preferred, as it provides similar functionality using an Elasticsearch point in time.

Return type:

AsyncIterator[_R]

script_fields(**kwargs)

Define script fields to be calculated on hits. See https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-script-fields.html for more details.

Example:

s = Search()
s = s.script_fields(times_two="doc['field'].value * 2")
s = s.script_fields(
    times_three={
        'script': {
            'lang': 'painless',
            'source': "doc['field'].value * params.n",
            'params': {'n': 3}
        }
    }
)
Parameters:

kwargs (Any)

Return type:

Self

search_after()

Return a Search instance that retrieves the next page of results.

This method provides an easy way to paginate a long list of results using the search_after option. For example:

page_size = 20
s = Search()[:page_size].sort("date")

while True:
    # get a page of results
    r = await s.execute()

    # do something with this page of results

    # exit the loop if we reached the end
    if len(r.hits) < page_size:
        break

    # get a search object with the next page of results
    s = s.search_after()

Note that the search_after option requires the search to have an explicit sort order.

Return type:

Self

sort(*keys)

Add sorting information to the search request. If called without arguments it will remove all sort requirements. Otherwise it will replace them. Acceptable arguments are:

'some.field'
'-some.other.field'
{'different.field': {'any': 'dict'}}

so for example:

s = Search().sort(
    'category',
    '-title',
    {"price" : {"order" : "asc", "mode" : "avg"}}
)

will sort by category, title (in descending order) and price in ascending order using the avg mode.

The API returns a copy of the Search object and can thus be chained.

Parameters:

keys (str | InstrumentedField | Dict[str, Dict[str, str]])

Return type:

Self

source(fields=None, **kwargs)

Selectively control how the _source field is returned.

Parameters:
  • fields (bool | str | InstrumentedField | List[str | InstrumentedField] | Dict[str, List[str | InstrumentedField]] | None) – field name, wildcard string, list of field names or wildcards, or dictionary of includes and excludes

  • kwargs (Any) – includes or excludes arguments, when fields is None.

  • fields

  • kwargs

Return type:

Self

When no arguments are given, the entire document will be returned for each hit. If fields is a string or list of strings, the field names or field wildcards given will be included. If fields is a dictionary with keys of ‘includes’ and/or ‘excludes’ the fields will be either included or excluded appropriately.

Calling this multiple times with the same named parameter will override the previous values with the new ones.

Example:

s = Search()
s = s.source(includes=['obj1.*'], excludes=["*.description"])

s = Search()
s = s.source(includes=['obj1.*']).source(excludes=["*.description"])
suggest(name, text=None, regex=None, **kwargs)

Add a suggestions request to the search.

Parameters:
  • name (str) – name of the suggestion

  • text (str | None) – text to suggest on

  • name

  • text

  • regex (str | None)

  • kwargs (Any)

Return type:

Self

All keyword arguments will be added to the suggestions body. For example:

s = Search()
s = s.suggest('suggestion-1', 'Elasticsearch', term={'field': 'body'})
# regex query for Completion Suggester

s = Search() s = s.suggest(‘suggestion-1’, regex=’py[thon|py]’, completion={‘field’: ‘body’})

to_dict(count=False, **kwargs)

Serialize the search into the dictionary that will be sent over as the request’s body.

Parameters:
  • count (bool) – a flag to specify if we are interested in a body for count - no aggregations, no pagination bounds etc.

  • count

  • kwargs (Any)

Return type:

Dict[str, Any]

All additional keyword arguments will be included into the dictionary.

update_from_dict(d)

Apply options from a serialized body to the current instance. Modifies the object in-place. Used mostly by from_dict.

Parameters:

d (Dict[str, Any])

Return type:

Self

using(client)

Associate the search request with an elasticsearch client. A fresh copy will be returned with current instance remaining unchanged.

Parameters:
Return type:

Self

Multi-Search
class elasticsearch.dsl.AsyncMultiSearch

Combine multiple Search objects into a single request.

__init__(**kwargs)
Parameters:

kwargs (Any)

add(search)

Adds a new Search object to the request:

ms = MultiSearch(index='my-index')
ms = ms.add(Search(doc_type=Category).filter('term', category='python'))
ms = ms.add(Search(doc_type=Blog))
Parameters:

search (SearchBase[_R])

Return type:

Self

doc_type(*doc_type, **kwargs)

Set the type to search through. You can supply a single value or multiple. Values can be strings or subclasses of Document.

You can also pass in any keyword arguments, mapping a doc_type to a callback that should be used instead of the Hit class.

If no doc_type is supplied any information stored on the instance will be erased.

Example:

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

Parameters:
Return type:

Self

async execute(ignore_cache=False, raise_on_error=True)

Execute the multi search request and return a list of search results.

Parameters:
  • ignore_cache (bool)

  • raise_on_error (bool)

Return type:

List[Response[_R]]

Add extra keys to the request body. Mostly here for backwards compatibility.

Parameters:

kwargs (Any)

Return type:

Self

index(*index)

Set the index for the search. If called empty it will remove all information.

Example:

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)

Specify query params to be used when executing the search. All the keyword arguments will override the current values. See https://elasticsearch-py.readthedocs.io/en/latest/api/elasticsearch.html#elasticsearch.Elasticsearch.search for all available parameters.

Example:

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

kwargs (Any)

Return type:

Self

using(client)

Associate the search request with an elasticsearch client. A fresh copy will be returned with current instance remaining unchanged.

Parameters:
Return type:

Self

Document
class elasticsearch.dsl.AsyncDocument

Model-like class for persisting documents in elasticsearch.

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

Allows to perform multiple indexing operations in a single request.

Parameters:
  • actions (AsyncIterable[Self | Dict[str, Any]]) – a generator that returns document instances to be indexed, bulk operation dictionaries.

  • using (str | AsyncElasticsearch | None) – connection alias to use, defaults to 'default'

  • index (str | None) – Elasticsearch index to use, if the Document is associated with an index this can be omitted.

  • validate (bool) – set to False to skip validating the documents

  • skip_empty (bool) – if set to False will cause empty values (None, [], {}) to be left on the document. Those values will be stripped out otherwise as they make no difference in Elasticsearch.

  • actions

  • using

  • index

  • validate

  • skip_empty

  • kwargs (Any)

Return type:

Tuple[int, int | List[Any]]

Any additional keyword arguments will be passed to Elasticsearch.bulk unchanged.

Returns:

bulk operation results

Parameters:
Return type:

Tuple[int, int | List[Any]]

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

Delete the instance in elasticsearch.

Parameters:
  • index (str | None) – elasticsearch index to use, if the Document is associated with an index this can be omitted.

  • using (str | AsyncElasticsearch | None) – connection alias to use, defaults to 'default'

  • using

  • index

  • kwargs (Any)

Return type:

None

Any additional keyword arguments will be passed to Elasticsearch.delete unchanged.

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

check if exists a single document from elasticsearch using its id.

Parameters:
  • id (str) – id of the document to check if exists

  • index (str | None) – elasticsearch index to use, if the Document is associated with an index this can be omitted.

  • using (str | AsyncElasticsearch | None) – connection alias to use, defaults to 'default'

  • id

  • using

  • index

  • kwargs (Any)

Return type:

bool

Any additional keyword arguments will be passed to Elasticsearch.exists unchanged.

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

Retrieve a single document from elasticsearch using its id.

Parameters:
  • id (str) – id of the document to be retrieved

  • index (str | None) – elasticsearch index to use, if the Document is associated with an index this can be omitted.

  • using (str | AsyncElasticsearch | None) – connection alias to use, defaults to 'default'

  • id

  • using

  • index

  • kwargs (Any)

Return type:

Self | None

Any additional keyword arguments will be passed to Elasticsearch.get unchanged.

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

Create the index and populate the mappings in elasticsearch.

Parameters:
Return type:

None

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

Retrieve multiple document by their ids. Returns a list of instances in the same order as requested.

Parameters:
  • docs (List[Dict[str, Any]]) – list of ids of the documents to be retrieved or a list of document specifications as per https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-multi-get.html

  • index (str | None) – elasticsearch index to use, if the Document is associated with an index this can be omitted.

  • using (str | AsyncElasticsearch | None) – connection alias to use, defaults to 'default'

  • missing (str) – what to do when one of the documents requested is not found. Valid options are 'none' (use None), 'raise' (raise NotFoundError) or 'skip' (ignore the missing document).

  • docs

  • using

  • index

  • raise_on_error (bool)

  • missing

  • kwargs (Any)

Return type:

List[Self | None]

Any additional keyword arguments will be passed to Elasticsearch.mget unchanged.

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

Save the document into elasticsearch. If the document doesn’t exist it is created, it is overwritten otherwise. Returns True if this operations resulted in new document being created.

Parameters:
  • index (str | None) – elasticsearch index to use, if the Document is associated with an index this can be omitted.

  • using (str | AsyncElasticsearch | None) – connection alias to use, defaults to 'default'

  • validate (bool) – set to False to skip validating the document

  • skip_empty (bool) – if set to False will cause empty values (None, [], {}) to be left on the document. Those values will be stripped out otherwise as they make no difference in elasticsearch.

  • return_doc_meta (bool) – set to True to return all metadata from the update API call instead of only the operation result

  • using

  • index

  • validate

  • skip_empty

  • return_doc_meta

  • kwargs (Any)

Return type:

Any

Any additional keyword arguments will be passed to Elasticsearch.index unchanged.

Returns:

operation result created/updated

Parameters:
Return type:

Any

classmethod search(using=None, index=None)

Create an Search instance that will search over this Document.

Parameters:
Return type:

AsyncSearch[Self]

to_dict(include_meta=False, skip_empty=True)

Serialize the instance into a dictionary so that it can be saved in elasticsearch.

Parameters:
  • include_meta (bool) – if set to True will include all the metadata (_index, _id etc). Otherwise just the document’s data is serialized. This is useful when passing multiple instances into elasticsearch.helpers.bulk.

  • skip_empty (bool) – if set to False will cause empty values (None, [], {}) to be left on the document. Those values will be stripped out otherwise as they make no difference in 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)

Partial update of the document, specify fields you wish to update and both the instance and the document in elasticsearch will be updated:

doc = MyDocument(title='Document Title!')
doc.save()
doc.update(title='New Document Title!')
Parameters:
  • index (str | None) – elasticsearch index to use, if the Document is associated with an index this can be omitted.

  • using (str | AsyncElasticsearch | None) – connection alias to use, defaults to 'default'

  • detect_noop (bool) – Set to False to disable noop detection.

  • refresh (bool) – Control when the changes made by this request are visible to search. Set to True for immediate effect.

  • retry_on_conflict (int | None) – In between the get and indexing phases of the update, it is possible that another process might have already updated the same document. By default, the update will fail with a version conflict exception. The retry_on_conflict parameter controls how many times to retry the update before finally throwing an exception.

  • doc_as_upsert (bool) – Instead of sending a partial doc plus an upsert doc, setting doc_as_upsert to true will use the contents of doc as the upsert value

  • script (str | Dict[str, Any] | None) – the source code of the script as a string, or a dictionary with script attributes to update.

  • return_doc_meta (bool) – set to True to return all metadata from the index API call instead of only the operation result

  • 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:

operation result noop/updated

Return type:

Any

Index
class elasticsearch.dsl.AsyncIndex
__init__(name, using='default')
Parameters:
  • name (str) – name of the index

  • using (str | AsyncElasticsearch) – connection alias to use, defaults to 'default'

  • name

  • using

aliases(**kwargs)

Add aliases to the index definition:

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

kwargs (Any)

Return type:

Self

async analyze(using=None, **kwargs)

Perform the analysis process on a text and return the tokens breakdown of the text.

Any additional keyword arguments will be passed to Elasticsearch.indices.analyze unchanged.

Parameters:
Return type:

ObjectApiResponse[Any]

analyzer(*args, **kwargs)

Explicitly add an analyzer to an index. Note that all custom analyzers defined in mappings will also be created. This is useful for search analyzers.

Example:

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)

Clear all caches or specific cached associated with the index.

Any additional keyword arguments will be passed to Elasticsearch.indices.clear_cache unchanged.

Parameters:
Return type:

ObjectApiResponse[Any]

clone(name=None, using=None)

Create a copy of the instance with another name or connection alias. Useful for creating multiple indices with shared configuration:

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

i2 = i.clone('other-index')
i2.create()
Parameters:
  • name (str | None) – name of the index

  • using (str | AsyncElasticsearch | None) – connection alias to use, defaults to 'default'

  • name

  • using

Return type:

Self

async close(using=None, **kwargs)

Closes the index in elasticsearch.

Any additional keyword arguments will be passed to Elasticsearch.indices.close unchanged.

Parameters:
Return type:

ObjectApiResponse[Any]

async create(using=None, **kwargs)

Creates the index in elasticsearch.

Any additional keyword arguments will be passed to Elasticsearch.indices.create unchanged.

Parameters:
Return type:

ObjectApiResponse[Any]

async delete(using=None, **kwargs)

Deletes the index in elasticsearch.

Any additional keyword arguments will be passed to Elasticsearch.indices.delete unchanged.

Parameters:
Return type:

ObjectApiResponse[Any]

async delete_alias(using=None, **kwargs)

Delete specific alias.

Any additional keyword arguments will be passed to Elasticsearch.indices.delete_alias unchanged.

Parameters:
Return type:

ObjectApiResponse[Any]

document(document)

Associate a Document subclass with an index. This means that, when this index is created, it will contain the mappings for the Document. If the Document class doesn’t have a default index yet (by defining class Index), this instance will be used. Can be used as a decorator:

i = Index('blog')

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

# create the index, including Post mappings
i.create()

# .search() will now return a Search object that will return
# properly deserialized Post instances
s = i.search()
Parameters:

document (DocumentMeta)

Return type:

DocumentMeta

async exists(using=None, **kwargs)

Returns True if the index already exists in elasticsearch.

Any additional keyword arguments will be passed to Elasticsearch.indices.exists unchanged.

Parameters:
Return type:

bool

async exists_alias(using=None, **kwargs)

Return a boolean indicating whether given alias exists for this index.

Any additional keyword arguments will be passed to Elasticsearch.indices.exists_alias unchanged.

Parameters:
Return type:

bool

async flush(using=None, **kwargs)

Performs a flush operation on the index.

Any additional keyword arguments will be passed to Elasticsearch.indices.flush unchanged.

Parameters:
Return type:

ObjectApiResponse[Any]

async forcemerge(using=None, **kwargs)

The force merge API allows to force merging of the index through an API. The merge relates to the number of segments a Lucene index holds within each shard. The force merge operation allows to reduce the number of segments by merging them.

This call will block until the merge is complete. If the http connection is lost, the request will continue in the background, and any new requests will block until the previous force merge is complete.

Any additional keyword arguments will be passed to Elasticsearch.indices.forcemerge unchanged.

Parameters:
Return type:

ObjectApiResponse[Any]

async get(using=None, **kwargs)

The get index API allows to retrieve information about the index.

Any additional keyword arguments will be passed to Elasticsearch.indices.get unchanged.

Parameters:
Return type:

ObjectApiResponse[Any]

async get_alias(using=None, **kwargs)

Retrieve a specified alias.

Any additional keyword arguments will be passed to Elasticsearch.indices.get_alias unchanged.

Parameters:
Return type:

ObjectApiResponse[Any]

async get_field_mapping(using=None, **kwargs)

Retrieve mapping definition of a specific field.

Any additional keyword arguments will be passed to Elasticsearch.indices.get_field_mapping unchanged.

Parameters:
Return type:

ObjectApiResponse[Any]

async get_mapping(using=None, **kwargs)

Retrieve specific mapping definition for a specific type.

Any additional keyword arguments will be passed to Elasticsearch.indices.get_mapping unchanged.

Parameters:
Return type:

ObjectApiResponse[Any]

async get_settings(using=None, **kwargs)

Retrieve settings for the index.

Any additional keyword arguments will be passed to Elasticsearch.indices.get_settings unchanged.

Parameters:
Return type:

ObjectApiResponse[Any]

mapping(mapping)

Associate a mapping (an instance of Mapping) with this index. This means that, when this index is created, it will contain the mappings for the document type defined by those mappings.

Parameters:

mapping (MappingBase)

Return type:

None

async open(using=None, **kwargs)

Opens the index in elasticsearch.

Any additional keyword arguments will be passed to Elasticsearch.indices.open unchanged.

Parameters:
Return type:

ObjectApiResponse[Any]

async put_alias(using=None, **kwargs)

Create an alias for the index.

Any additional keyword arguments will be passed to Elasticsearch.indices.put_alias unchanged.

Parameters:
Return type:

ObjectApiResponse[Any]

async put_mapping(using=None, **kwargs)

Register specific mapping definition for a specific type.

Any additional keyword arguments will be passed to Elasticsearch.indices.put_mapping unchanged.

Parameters:
Return type:

ObjectApiResponse[Any]

async put_settings(using=None, **kwargs)

Change specific index level settings in real time.

Any additional keyword arguments will be passed to Elasticsearch.indices.put_settings unchanged.

Parameters:
Return type:

ObjectApiResponse[Any]

async recovery(using=None, **kwargs)

The indices recovery API provides insight into on-going shard recoveries for the index.

Any additional keyword arguments will be passed to Elasticsearch.indices.recovery unchanged.

Parameters:
Return type:

ObjectApiResponse[Any]

async refresh(using=None, **kwargs)

Performs a refresh operation on the index.

Any additional keyword arguments will be passed to Elasticsearch.indices.refresh unchanged.

Parameters:
Return type:

ObjectApiResponse[Any]

async save(using=None)

Sync the index definition with elasticsearch, creating the index if it doesn’t exist and updating its settings and mappings if it does.

Note some settings and mapping changes cannot be done on an open index (or at all on an existing index) and for those this method will fail with the underlying exception.

Parameters:

using (str | AsyncElasticsearch | None)

Return type:

Optional[ObjectApiResponse[Any]]

search(using=None)

Return a Search object searching over the index (or all the indices belonging to this template) and its Documents.

Parameters:

using (str | AsyncElasticsearch | None)

Return type:

AsyncSearch

async segments(using=None, **kwargs)

Provide low level segments information that a Lucene index (shard level) is built with.

Any additional keyword arguments will be passed to Elasticsearch.indices.segments unchanged.

Parameters:
Return type:

ObjectApiResponse[Any]

settings(**kwargs)

Add settings to the index:

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

Multiple calls to settings will merge the keys, later overriding the earlier.

Parameters:

kwargs (Any)

Return type:

Self

async shard_stores(using=None, **kwargs)

Provides store information for shard copies of the index. Store information reports on which nodes shard copies exist, the shard copy version, indicating how recent they are, and any exceptions encountered while opening the shard index or from earlier engine failure.

Any additional keyword arguments will be passed to Elasticsearch.indices.shard_stores unchanged.

Parameters:
Return type:

ObjectApiResponse[Any]

async shrink(using=None, **kwargs)

The shrink index API allows you to shrink an existing index into a new index with fewer primary shards. The number of primary shards in the target index must be a factor of the shards in the source index. For example an index with 8 primary shards can be shrunk into 4, 2 or 1 primary shards or an index with 15 primary shards can be shrunk into 5, 3 or 1. If the number of shards in the index is a prime number it can only be shrunk into a single primary shard. Before shrinking, a (primary or replica) copy of every shard in the index must be present on the same node.

Any additional keyword arguments will be passed to Elasticsearch.indices.shrink unchanged.

Parameters:
Return type:

ObjectApiResponse[Any]

async stats(using=None, **kwargs)

Retrieve statistics on different operations happening on the index.

Any additional keyword arguments will be passed to Elasticsearch.indices.stats unchanged.

Parameters:
Return type:

ObjectApiResponse[Any]

updateByQuery(using=None)

Return a UpdateByQuery object searching over the index (or all the indices belonging to this template) and updating Documents that match the search criteria.

For more information, see here: 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)

Validate a potentially expensive query without executing it.

Any additional keyword arguments will be passed to Elasticsearch.indices.validate_query unchanged.

Parameters:
Return type:

ObjectApiResponse[Any]

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

None

Faceted Search
class elasticsearch.dsl.AsyncFacetedSearch
__init__(query=None, filters={}, sort=[])
Parameters:
  • query (str | Query | None) – the text to search for

  • filters (Dict[str, str | int | float | bool]) – facet values to filter

  • sort (Sequence[str]) – sort information to be passed to Search

  • query

  • filters

  • sort

add_filter(name, filter_values)

Add a filter for a facet.

Parameters:
Return type:

None

aggregate(search)

Add aggregations representing the facets selected, including potential filters.

Parameters:

search (SearchBase[_R])

Return type:

None

build_search()

Construct the Search object.

Return type:

SearchBase[_R]

async execute()

Execute the search and return the response.

Return type:

Response[_R]

filter(search)

Add a post_filter to the search request narrowing the results based on the facet filters.

Parameters:

search (SearchBase[_R])

Return type:

SearchBase[_R]

highlight(search)

Add highlighting for all the fields

Parameters:

search (SearchBase[_R])

Return type:

SearchBase[_R]

params(**kwargs)

Specify query params to be used when executing the search. All the keyword arguments will override the current values. See https://elasticsearch-py.readthedocs.io/en/latest/api/elasticsearch.html#elasticsearch.Elasticsearch.search for all available parameters.

Parameters:

kwargs (Any)

Return type:

None

query(search, query)

Add query part to search.

Override this if you wish to customize the query used.

Parameters:
  • search (SearchBase[_R])

  • query (str | Query)

Return type:

SearchBase[_R]

search()

Returns the base Search object to which the facets are added.

You can customize the query by overriding this method and returning a modified search object.

Return type:

AsyncSearch[_R]

sort(search)

Add sorting information to the request.

Parameters:

search (SearchBase[_R])

Return type:

SearchBase[_R]

Update by Query
class elasticsearch.dsl.AsyncUpdateByQuery
__init__(**kwargs)

Update by query request to elasticsearch.

Parameters:
  • usingElasticsearch instance to use

  • index – limit the search to index

  • doc_type – only query this type.

  • kwargs (Any)

All the parameters supplied (or omitted) at creation type can be later overridden by methods (using, index and doc_type respectively).

doc_type(*doc_type, **kwargs)

Set the type to search through. You can supply a single value or multiple. Values can be strings or subclasses of Document.

You can also pass in any keyword arguments, mapping a doc_type to a callback that should be used instead of the Hit class.

If no doc_type is supplied any information stored on the instance will be erased.

Example:

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

Parameters:
Return type:

Self

async execute()

Execute the search and return an instance of Response wrapping all the data.

Return type:

UpdateByQueryResponse[_R]

Add extra keys to the request body. Mostly here for backwards compatibility.

Parameters:

kwargs (Any)

Return type:

Self

classmethod from_dict(d)

Construct a new UpdateByQuery instance from a raw dict containing the search body. Useful when migrating from raw dictionaries.

Example:

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

d (Dict[str, Any])

Return type:

Self

index(*index)

Set the index for the search. If called empty it will remove all information.

Example:

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)

Specify query params to be used when executing the search. All the keyword arguments will override the current values. See https://elasticsearch-py.readthedocs.io/en/latest/api/elasticsearch.html#elasticsearch.Elasticsearch.search for all available parameters.

Example:

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

kwargs (Any)

Return type:

Self

response_class(cls)

Override the default wrapper used for the response.

Parameters:

cls (Type[UpdateByQueryResponse[_R]])

Return type:

Self

script(**kwargs)

Define update action to take: https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-scripting-using.html for more details.

Note: the API only accepts a single script, so calling the script multiple times will overwrite.

Example:

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)

Serialize the search into the dictionary that will be sent over as the request’ubq body.

All additional keyword arguments will be included into the dictionary.

Parameters:

kwargs (Any)

Return type:

Dict[str, Any]

update_from_dict(d)

Apply options from a serialized body to the current instance. Modifies the object in-place. Used mostly by from_dict.

Parameters:

d (Dict[str, Any])

Return type:

Self

using(client)

Associate the search request with an elasticsearch client. A fresh copy will be returned with current instance remaining unchanged.

Parameters:
Return type:

Self


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4