OpenSearch Python Client Logo
  • API Reference
    • Clients
    • Connection Types
    • connection_pool
    • exceptions
    • helpers
      • aggs
      • analysis
      • document
      • faceted_search
      • field
      • function
      • index
      • mapping
      • query
      • search
        • Search
      • update_by_query
      • wrappers
    • metrics
    • Plugins
    • serializer
    • transport
  • Index
  • License
  • Contributing
  • Code of Conduct
  • Developer Guide
  • GitHub Repository
OpenSearch Python Client
  • API Reference
  • helpers
  • search
  • Edit on GitHub

search

class opensearchpy.helpers.search.Search(**kwargs)[source]

Bases: Request

Search request to opensearch.

Parameters:
  • using – OpenSearch 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).

__getitem__(n)[source]

Support slicing the Search instance for pagination.

Slicing equates to the from/size parameters. E.g.:

s = Search().query(...)[0:25]

is equivalent to:

s = Search().query(...).extra(from_=0, size=25)
Parameters:

n (Any) –

Return type:

Any

__iter__()[source]

Iterate over the hits.

Return type:

Any

_clone()[source]

Return a clone of the current search request. Performs a shallow copy of all the underlying objects. Used internally by most state modifying APIs.

Return type:

Any

collapse(field=None, inner_hits=None, max_concurrent_group_searches=None)[source]

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 (Any | None) –

  • inner_hits (Any | None) –

  • max_concurrent_group_searches (Any | None) –

Return type:

Any

count()[source]

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

Return type:

Any

delete() executes the query by delegating to delete_by_query()[source]
Return type:

Any

execute(ignore_cache=False)[source]

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 OpenSearch, while cached result will be ignored. Defaults to False

  • ignore_cache –

Return type:

Any

classmethod from_dict(d)[source]

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 (Any) –

Return type:

Any

highlight(*fields, **kwargs)[source]

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 (Any) –

  • kwargs (Any) –

Return type:

Any

highlight_options(**kwargs)[source]

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

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

kwargs (Any) –

Return type:

Any

response_class(cls)[source]

Override the default wrapper used for the response.

Parameters:

cls (Any) –

Return type:

Any

scan()[source]

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

Use params method to specify any additional arguments you with to pass to the underlying scan helper from opensearchpy

Return type:

Any

script_fields(**kwargs)[source]

Define script fields to be calculated on hits.

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:

Any

sort(*keys)[source]

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 (Any) –

Return type:

Any

source(fields=None, **kwargs)[source]

Selectively control how the _source field is returned.

Parameters:
  • fields (Any | None) – wildcard string, array of wildcards, or dictionary of includes and excludes

  • fields –

  • kwargs (Any) –

Return type:

Any

If fields is None, the entire document will be returned for each hit. 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, **kwargs)[source]

Add a suggestions request to the search.

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

  • text (Any) – text to suggest on

  • name –

  • text –

  • kwargs (Any) –

Return type:

Any

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

s = Search()
s = s.suggest('suggestion-1', 'OpenSearch', term={'field': 'body'})
to_dict(count=False, **kwargs)[source]

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:

Any

All additional keyword arguments will be included into the dictionary.

update_from_dict(d)[source]

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

Parameters:

d (Any) –

Return type:

Search

Previous Next

© Copyright OpenSearch Project Contributors.