desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Add aliases to the index definition::
i = Index(\'blog-v2\')
i.aliases(blog={}, published={\'filter\': Q(\'term\', published=True)})'
| def aliases(self, **kwargs):
| self._aliases.update(kwargs)
return self
|
'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),
... | def analyzer(self, analyzer):
| d = analyzer.get_analysis_definition()
if (not d):
return
for key in d:
self._analysis.setdefault(key, {}).update(d[key])
|
'Return a :class:`~elasticsearch_dsl.Search` object searching over all
the indices belonging to this template and its ``DocType``\s.'
| def search(self):
| return Search(using=self._using, index=self._template, doc_type=[self._doc_types.get(k, k) for k in self._mappings])
|
'Return a :class:`~elasticsearch_dsl.Search` object searching over this
index and its ``DocType``\s.'
| def search(self):
| return Search(using=self._using, index=self._name, doc_type=[self._doc_types.get(k, k) for k in self._mappings])
|
'Creates the index in elasticsearch.
Any additional keyword arguments will be passed to
``Elasticsearch.indices.create`` unchanged.'
| def create(self, **kwargs):
| self.connection.indices.create(index=self._name, body=self.to_dict(), **kwargs)
|
'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.'
| def save(self):
| if (not self.exists()):
return self.create()
body = self.to_dict()
settings = body.pop('settings', {})
analysis = settings.pop('analysis', None)
if analysis:
if self.is_closed():
settings['analysis'] = analysis
else:
existing_analysis = self.get_settin... |
'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.'
| def analyze(self, **kwargs):
| return self.connection.indices.analyze(index=self._name, **kwargs)
|
'Preforms a refresh operation on the index.
Any additional keyword arguments will be passed to
``Elasticsearch.indices.refresh`` unchanged.'
| def refresh(self, **kwargs):
| return self.connection.indices.refresh(index=self._name, **kwargs)
|
'Preforms a flush operation on the index.
Any additional keyword arguments will be passed to
``Elasticsearch.indices.flush`` unchanged.'
| def flush(self, **kwargs):
| return self.connection.indices.flush(index=self._name, **kwargs)
|
'The get index API allows to retrieve information about the index.
Any additional keyword arguments will be passed to
``Elasticsearch.indices.get`` unchanged.'
| def get(self, **kwargs):
| return self.connection.indices.get(index=self._name, **kwargs)
|
'Opens the index in elasticsearch.
Any additional keyword arguments will be passed to
``Elasticsearch.indices.open`` unchanged.'
| def open(self, **kwargs):
| return self.connection.indices.open(index=self._name, **kwargs)
|
'Closes the index in elasticsearch.
Any additional keyword arguments will be passed to
``Elasticsearch.indices.close`` unchanged.'
| def close(self, **kwargs):
| return self.connection.indices.close(index=self._name, **kwargs)
|
'Deletes the index in elasticsearch.
Any additional keyword arguments will be passed to
``Elasticsearch.indices.delete`` unchanged.'
| def delete(self, **kwargs):
| return self.connection.indices.delete(index=self._name, **kwargs)
|
'Returns ``True`` if the index already exists in elasticsearch.
Any additional keyword arguments will be passed to
``Elasticsearch.indices.exists`` unchanged.'
| def exists(self, **kwargs):
| return self.connection.indices.exists(index=self._name, **kwargs)
|
'Check if a type/types exists in the index.
Any additional keyword arguments will be passed to
``Elasticsearch.indices.exists_type`` unchanged.'
| def exists_type(self, **kwargs):
| return self.connection.indices.exists_type(index=self._name, **kwargs)
|
'Register specific mapping definition for a specific type.
Any additional keyword arguments will be passed to
``Elasticsearch.indices.put_mapping`` unchanged.'
| def put_mapping(self, **kwargs):
| return self.connection.indices.put_mapping(index=self._name, **kwargs)
|
'Retrieve specific mapping definition for a specific type.
Any additional keyword arguments will be passed to
``Elasticsearch.indices.get_mapping`` unchanged.'
| def get_mapping(self, **kwargs):
| return self.connection.indices.get_mapping(index=self._name, **kwargs)
|
'Retrieve mapping definition of a specific field.
Any additional keyword arguments will be passed to
``Elasticsearch.indices.get_field_mapping`` unchanged.'
| def get_field_mapping(self, **kwargs):
| return self.connection.indices.get_field_mapping(index=self._name, **kwargs)
|
'Create an alias for the index.
Any additional keyword arguments will be passed to
``Elasticsearch.indices.put_alias`` unchanged.'
| def put_alias(self, **kwargs):
| return self.connection.indices.put_alias(index=self._name, **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.'
| def exists_alias(self, **kwargs):
| return self.connection.indices.exists_alias(index=self._name, **kwargs)
|
'Retrieve a specified alias.
Any additional keyword arguments will be passed to
``Elasticsearch.indices.get_alias`` unchanged.'
| def get_alias(self, **kwargs):
| return self.connection.indices.get_alias(index=self._name, **kwargs)
|
'Delete specific alias.
Any additional keyword arguments will be passed to
``Elasticsearch.indices.delete_alias`` unchanged.'
| def delete_alias(self, **kwargs):
| return self.connection.indices.delete_alias(index=self._name, **kwargs)
|
'Retrieve settings for the index.
Any additional keyword arguments will be passed to
``Elasticsearch.indices.get_settings`` unchanged.'
| def get_settings(self, **kwargs):
| return self.connection.indices.get_settings(index=self._name, **kwargs)
|
'Change specific index level settings in real time.
Any additional keyword arguments will be passed to
``Elasticsearch.indices.put_settings`` unchanged.'
| def put_settings(self, **kwargs):
| return self.connection.indices.put_settings(index=self._name, **kwargs)
|
'Retrieve statistics on different operations happening on the index.
Any additional keyword arguments will be passed to
``Elasticsearch.indices.stats`` unchanged.'
| def stats(self, **kwargs):
| return self.connection.indices.stats(index=self._name, **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.'
| def segments(self, **kwargs):
| return self.connection.indices.segments(index=self._name, **kwargs)
|
'Validate a potentially expensive query without executing it.
Any additional keyword arguments will be passed to
``Elasticsearch.indices.validate_query`` unchanged.'
| def validate_query(self, **kwargs):
| return self.connection.indices.validate_query(index=self._name, **kwargs)
|
'Clear all caches or specific cached associated with the index.
Any additional keyword arguments will be passed to
``Elasticsearch.indices.clear_cache`` unchanged.'
| def clear_cache(self, **kwargs):
| return self.connection.indices.clear_cache(index=self._name, **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.'
| def recovery(self, **kwargs):
| return self.connection.indices.recovery(index=self._name, **kwargs)
|
'Upgrade the index to the latest format.
Any additional keyword arguments will be passed to
``Elasticsearch.indices.upgrade`` unchanged.'
| def upgrade(self, **kwargs):
| return self.connection.indices.upgrade(index=self._name, **kwargs)
|
'Monitor how much of the index is upgraded.
Any additional keyword arguments will be passed to
``Elasticsearch.indices.get_upgrade`` unchanged.'
| def get_upgrade(self, **kwargs):
| return self.connection.indices.get_upgrade(index=self._name, **kwargs)
|
'Perform a normal flush, then add a generated unique marker (sync_id) to
all shards.
Any additional keyword arguments will be passed to
``Elasticsearch.indices.flush_synced`` unchanged.'
| def flush_synced(self, **kwargs):
| return self.connection.indices.flush_synced(index=self._name, **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
... | def shard_stores(self, **kwargs):
| return self.connection.indices.shard_stores(index=self._name, **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 los... | def forcemerge(self, **kwargs):
| return self.connection.indices.forcemerge(index=self._name, **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... | def shrink(self, **kwargs):
| return self.connection.indices.shrink(index=self._name, **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/master/api.html#elasticsearch.Elasticsearch.search
for all available parameters.
Example::
s = Search()
s = s.params(routing=\'user-1\', preference=\'loc... | def params(self, **kwargs):
| s = self._clone()
s._params.update(kwargs)
return s
|
'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\'])'
| def index(self, *index):
| s = self._clone()
if (not index):
s._index = None
else:
indexes = []
for i in index:
if isinstance(i, str):
indexes.append(i)
elif isinstance(i, list):
indexes += i
elif isinstance(i, tuple):
indexes ... |
'Set the type to search through. You can supply a single value or
multiple. Values can be strings or subclasses of ``DocType``.
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 wil... | def doc_type(self, *doc_type, **kwargs):
| s = self._clone()
if ((not doc_type) and (not kwargs)):
s._doc_type = []
s._doc_type_map = {}
else:
for dt in doc_type:
s._add_doc_type(dt)
s._doc_type.extend(kwargs.keys())
s._doc_type_map.update(kwargs)
return s
|
'Associate the search request with an elasticsearch client. A fresh copy
will be returned with current instance remaining unchanged.
:arg client: an instance of ``elasticsearch.Elasticsearch`` to use or
an alias to look up in ``elasticsearch_dsl.connections``'
| def using(self, client):
| s = self._clone()
s._using = client
return s
|
'Add extra keys to the request body. Mostly here for backwards
compatibility.'
| def extra(self, **kwargs):
| s = self._clone()
if ('from_' in kwargs):
kwargs['from'] = kwargs.pop('from_')
s._extra.update(kwargs)
return s
|
'Search request to elasticsearch.
:arg using: `Elasticsearch` instance to use
:arg index: limit the search to index
:arg doc_type: only query this type.
All the parameters supplied (or omitted) at creation type can be later
overriden by methods (`using`, `index` and `doc_type` respectively).'
| def __init__(self, **kwargs):
| super(Search, self).__init__(**kwargs)
self.aggs = AggsProxy(self)
self._sort = []
self._source = None
self._highlight = {}
self._highlight_opts = {}
self._suggest = {}
self._script_fields = {}
self._response_class = Response
self._query_proxy = QueryProxy(self, 'query')
self... |
'Iterate over the hits.'
| def __iter__(self):
| return iter(self.execute())
|
'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)'
| def __getitem__(self, n):
| s = self._clone()
if isinstance(n, slice):
if ((n.start and (n.start < 0)) or (n.stop and (n.stop < 0))):
raise ValueError('Search does not support negative slicing.')
s._extra['from'] = (n.start or 0)
s._extra['size'] = ((n.stop - (n.start or 0)) if (n.stop is... |
'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)'
| @classmethod
def from_dict(cls, d):
| s = cls()
s.update_from_dict(d)
return s
|
'Return a clone of the current search request. Performs a shallow copy
of all the underlying objects. Used internally by most state modifying
APIs.'
| def _clone(self):
| s = super(Search, self)._clone()
s._response_class = self._response_class
s._sort = self._sort[:]
s._source = (copy.copy(self._source) if (self._source is not None) else None)
s._highlight = self._highlight.copy()
s._highlight_opts = self._highlight_opts.copy()
s._suggest = self._suggest.cop... |
'Override the default wrapper used for the response.'
| def response_class(self, cls):
| s = self._clone()
s._response_class = cls
return s
|
'Apply options from a serialized body to the current instance. Modifies
the object in-place. Used mostly by ``from_dict``.'
| def update_from_dict(self, d):
| d = d.copy()
if ('query' in d):
self.query._proxied = Q(d.pop('query'))
if ('post_filter' in d):
self.post_filter._proxied = Q(d.pop('post_filter'))
aggs = d.pop('aggs', d.pop('aggregations', {}))
if aggs:
self.aggs._params = {'aggs': dict(((name, A(value)) for (name, value) ... |
'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\': "doc[\'field\'].value * ... | def script_fields(self, **kwargs):
| s = self._clone()
for name in kwargs:
if isinstance(kwargs[name], string_types):
kwargs[name] = {'script': kwargs[name]}
s._script_fields.update(kwargs)
return s
|
'Selectively control how the _source field is returned.
:arg source: wildcard string, array of wildcards, or dictionary of includes and excludes
If ``source`` is None, the entire document will be returned for
each hit. If source is a dictionary with keys of \'include\' and/or
\'exclude\' the fields will be either incl... | def source(self, fields=None, **kwargs):
| s = self._clone()
if (fields and kwargs):
raise ValueError('You cannot specify fields and kwargs at the same time.')
if (fields is not None):
s._source = fields
return s
if (kwargs and (not isinstance(s._source, dict))):
s._source = {}
for (... |
'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\',
{"pri... | def sort(self, *keys):
| s = self._clone()
s._sort = []
for k in keys:
if (isinstance(k, string_types) and k.startswith('-')):
k = {k[1:]: {'order': 'desc'}}
s._sort.append(k)
return s
|
'Update the global highlighting options used for this request. For
example::
s = Search()
s = s.highlight_options(order=\'score\')'
| def highlight_options(self, **kwargs):
| s = self._clone()
s._highlight_opts.update(kwargs)
return s
|
'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": {"fragm... | def highlight(self, *fields, **kwargs):
| s = self._clone()
for f in fields:
s._highlight[f] = kwargs
return s
|
'Add a suggestions request to the search.
:arg name: name of the suggestion
:arg text: text to suggest on
All keyword arguments will be added to the suggestions body. For example::
s = Search()
s = s.suggest(\'suggestion-1\', \'Elasticsearch\', term={\'field\': \'body\'})'
| def suggest(self, name, text, **kwargs):
| s = self._clone()
s._suggest[name] = {'text': text}
s._suggest[name].update(kwargs)
return s
|
'Serialize the search into the dictionary that will be sent over as the
request\'s body.
:arg count: a flag to specify we are interested in a body for count -
no aggregations, no pagination bounds etc.
All additional keyword arguments will be included into the dictionary.'
| def to_dict(self, count=False, **kwargs):
| d = {'query': self.query.to_dict()}
if (not count):
if self.post_filter:
d['post_filter'] = self.post_filter.to_dict()
if self.aggs.aggs:
d.update(self.aggs.to_dict())
if self._sort:
d['sort'] = self._sort
d.update(self._extra)
if (self... |
'Return the number of hits matching the query and filters. Note that
only the actual number is returned.'
| def count(self):
| if hasattr(self, '_response'):
return self._response.hits.total
es = connections.get_connection(self._using)
d = self.to_dict(count=True)
return es.count(index=self._index, doc_type=self._doc_type, body=d, **self._params)['count']
|
'Execute the search and return an instance of ``Response`` wrapping all
the data.
:arg response_class: optional subclass of ``Response`` to use instead.'
| def execute(self, ignore_cache=False):
| if (ignore_cache or (not hasattr(self, '_response'))):
es = connections.get_connection(self._using)
self._response = self._response_class(self, es.search(index=self._index, doc_type=self._doc_type, body=self.to_dict(), **self._params))
return self._response
|
'Execute just the suggesters. Ignores all parts of the request that are
not relevant, including ``query`` and ``doc_type``.'
| def execute_suggest(self):
| es = connections.get_connection(self._using)
return SuggestResponse(es.suggest(index=self._index, body=self._suggest, **self._params))
|
'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 ``elasticsearch-py`` -
https://elasticsearch-py.readthedocs.io/en/master/helpers.html#... | def scan(self):
| es = connections.get_connection(self._using)
for hit in scan(es, query=self.to_dict(), index=self._index, doc_type=self._doc_type, **self._params):
callback = self._doc_type_map.get(hit['_type'], Hit)
callback = getattr(callback, 'from_es', callback)
(yield callback(hit))
|
'delete() executes the query by delegating to delete_by_query()'
| def delete(self):
| es = connections.get_connection(self._using)
return AttrDict(es.delete_by_query(index=self._index, body=self.to_dict(), doc_type=self._doc_type, **self._params))
|
'Adds a new :class:`~elasticsearch_dsl.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))'
| def add(self, search):
| ms = self._clone()
ms._searches.append(search)
return ms
|
'Execute the multi search request and return a list of search results.'
| def execute(self, ignore_cache=False, raise_on_error=True):
| if (ignore_cache or (not hasattr(self, '_response'))):
es = connections.get_connection(self._using)
responses = es.msearch(index=self._index, doc_type=self._doc_type, body=self.to_dict(), **self._params)
out = []
for (s, r) in zip(self._searches, responses['responses']):
... |
'Produce a repr of all our parameters to be used in __repr__.'
| def _repr_params(self):
| return u', '.join(((u'%s=%r' % (n.replace(u'.', u'__'), v)) for (n, v) in sorted(iteritems(self._params)) if ((u'type' not in self._param_defs.get(n, {})) or v)))
|
'Serialize the DSL object to plain dict'
| def to_dict(self):
| d = {}
for (pname, value) in iteritems(self._params):
pinfo = self._param_defs.get(pname)
if (pinfo and (u'type' in pinfo)):
if (value in ({}, [])):
continue
if pinfo.get(u'multi'):
value = list(map((lambda x: x.to_dict()), value))
... |
'Iterate over all Field objects within, including multi fields.'
| def _collect_fields(self):
| for f in itervalues(self.properties.to_dict()):
(yield f)
if hasattr(f, 'fields'):
for inner_f in itervalues(f.fields.to_dict()):
(yield inner_f)
if hasattr(f, '_collect_fields'):
for inner_f in f._collect_fields():
(yield inner_f)
|
'Return the aggregation object.'
| def get_aggregation(self):
| return A(self.agg_type, **self._params)
|
'Construct a filter.'
| def add_filter(self, filter_values):
| if (not filter_values):
return
f = self.get_value_filter(filter_values[0])
for v in filter_values[1:]:
f |= self.get_value_filter(v)
return f
|
'Construct a filter for an individual value'
| def get_value_filter(self, filter_value):
| pass
|
'Is a filter active on the given key.'
| def is_filtered(self, key, filter_values):
| return (key in filter_values)
|
'return a value representing a bucket. Its key as default.'
| def get_value(self, bucket):
| return bucket['key']
|
'Turn the raw bucket data into a list of tuples containing the key,
number of documents and a flag indicating whether this value has been
selected or not.'
| def get_values(self, data, filter_values):
| out = []
for bucket in data:
key = self.get_value(bucket)
out.append((key, bucket['doc_count'], self.is_filtered(key, filter_values)))
return out
|
'Create a terms filter instead of bool containing term filters.'
| def add_filter(self, filter_values):
| if filter_values:
return Q('terms', **{self._params['field']: filter_values})
|
':arg query: the text to search for
:arg filters: facet values to filter
:arg sort: sort information to be passed to :class:`~elasticsearch_dsl.Search`'
| def __init__(self, query=None, filters={}, sort=()):
| self._query = query
self._filters = {}
if isinstance(sort, string_types):
self._sort = (sort,)
else:
self._sort = sort
self.filter_values = {}
for (name, value) in iteritems(filters):
self.add_filter(name, value)
self._s = self.build_search()
|
'Add a filter for a facet.'
| def add_filter(self, name, filter_values):
| if (not isinstance(filter_values, (tuple, list))):
if (filter_values is None):
return
filter_values = [filter_values]
self.filter_values[name] = filter_values
f = self.facets[name].add_filter(filter_values)
if (f is None):
return
self._filters[name] = f
|
'Construct the Search object.'
| def search(self):
| s = Search(doc_type=self.doc_types, index=self.index)
return s.response_class(FacetedResponse)
|
'Add query part to ``search``.
Override this if you wish to customize the query used.'
| def query(self, search, query):
| if query:
return search.query('multi_match', fields=self.fields, query=query)
return search
|
'Add aggregations representing the facets selected, including potential
filters.'
| def aggregate(self, search):
| for (f, facet) in iteritems(self.facets):
agg = facet.get_aggregation()
agg_filter = Q('match_all')
for (field, filter) in iteritems(self._filters):
if (f == field):
continue
agg_filter &= filter
search.aggs.bucket(('_filter_' + f), 'filter', f... |
'Add a ``post_filter`` to the search request narrowing the results based
on the facet filters.'
| def filter(self, search):
| post_filter = Q('match_all')
for f in itervalues(self._filters):
post_filter &= f
return search.post_filter(post_filter)
|
'Add highlighting for all the fields'
| def highlight(self, search):
| return search.highlight(*((f if ('^' not in f) else f.split('^', 1)[0]) for f in self.fields))
|
'Add sorting information to the request.'
| def sort(self, search):
| if self._sort:
search = search.sort(*self._sort)
return search
|
'Construct the ``Search`` object.'
| def build_search(self):
| s = self.search()
s = self.query(s, self._query)
s = self.filter(s)
s = self.highlight(s)
s = self.sort(s)
self.aggregate(s)
return s
|
'Execute the search and return the response.'
| def execute(self):
| r = self._s.execute()
r._faceted_search = self
return r
|
'Create the index and populate the mappings in elasticsearch.'
| @classmethod
def init(cls, index=None, using=None):
| cls._doc_type.init(index, using)
|
'Create an :class:`~elasticsearch_dsl.Search` instance that will search
over this ``DocType``.'
| @classmethod
def search(cls, using=None, index=None):
| return Search(using=(using or cls._doc_type.using), index=(index or cls._doc_type.index), doc_type=[cls])
|
'Retrieve a single document from elasticsearch using it\'s ``id``.
:arg id: ``id`` of the document to be retireved
:arg index: elasticsearch index to use, if the ``DocType`` is
associated with an index this can be omitted.
:arg using: connection alias to use, defaults to ``\'default\'``
Any additional keyword arguments... | @classmethod
def get(cls, id, using=None, index=None, **kwargs):
| es = connections.get_connection((using or cls._doc_type.using))
doc = es.get(index=(index or cls._doc_type.index), doc_type=cls._doc_type.name, id=id, **kwargs)
if (not doc['found']):
return None
return cls.from_es(doc)
|
'Retrieve multiple document by their ``id``\s. Returns a list of instances
in the same order as requested.
:arg docs: list of ``id``\s of the documents to be retireved or a list
of document specifications as per
https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-multi-get.html
:arg index: elasticsearc... | @classmethod
def mget(cls, docs, using=None, index=None, raise_on_error=True, missing='none', **kwargs):
| if (missing not in ('raise', 'skip', 'none')):
raise ValueError("'missing' must be 'raise', 'skip', or 'none'.")
es = connections.get_connection((using or cls._doc_type.using))
body = {'docs': [(doc if isinstance(doc, collections.Mapping) else {'_id': doc}) for doc in docs]}
re... |
'Helper method to construct an instance from a dictionary returned by
elasticsearch.'
| @classmethod
def from_es(cls, hit):
| meta = hit.copy()
doc = meta.pop('_source', {})
if ('fields' in meta):
for (k, v) in iteritems(meta.pop('fields')):
if (k == '_source'):
doc.update(v)
if (k.startswith('_') and (k[1:] in META_FIELDS)):
meta[k] = v
else:
... |
'Delete the instance in elasticsearch.
:arg index: elasticsearch index to use, if the ``DocType`` is
associated with an index this can be omitted.
:arg using: connection alias to use, defaults to ``\'default\'``
Any additional keyword arguments will be passed to
``Elasticsearch.delete`` unchanged.'
| def delete(self, using=None, index=None, **kwargs):
| es = self._get_connection(using)
doc_meta = dict(((k, self.meta[k]) for k in DELETE_META_FIELDS if (k in self.meta)))
doc_meta.update(kwargs)
es.delete(index=self._get_index(index), doc_type=self._doc_type.name, **doc_meta)
|
'Serialize the instance into a dictionary so that it can be saved in elasticsearch.
:arg include_meta: if set to ``True`` will include all the metadata
(``_index``, ``_type``, ``_id`` etc). Otherwise just the document\'s
data is serialized. This is useful when passing multiple instances into
``elasticsearch.helpers.bul... | def to_dict(self, include_meta=False):
| d = super(DocType, self).to_dict()
if (not include_meta):
return d
meta = dict(((('_' + k), self.meta[k]) for k in DOC_META_FIELDS if (k in self.meta)))
if ('index' in self.meta):
meta['_index'] = self.meta.index
elif self._doc_type.index:
meta['_index'] = self._doc_type.inde... |
'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!\')
:arg index: elasticsearch index to use, if the ``DocType`` is
associated with an i... | def update(self, using=None, index=None, detect_noop=True, doc_as_upsert=False, **fields):
| if (not fields):
raise IllegalOperation('You cannot call update() without updating individual fields. If you wish to update the entire object use save().')
es = self._get_connection(using)
merge(self._d_, fields)
values = self.to_dict()
doc ... |
'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.
:arg index: elasticsearch index to use, if the ``DocType`` is
associated with an index this can be omitted.
:arg using: connection... | def save(self, using=None, index=None, validate=True, **kwargs):
| if validate:
self.full_clean()
es = self._get_connection(using)
doc_meta = dict(((k, self.meta[k]) for k in DOC_META_FIELDS if (k in self.meta)))
doc_meta.update(kwargs)
meta = es.index(index=self._get_index(index), doc_type=self._doc_type.name, body=self.to_dict(), **doc_meta)
for k in ... |
'Configure multiple connections at once, useful for passing in config
dictionaries obtained from other sources, like Django\'s settings or a
configuration management tool.
Example::
connections.configure(
default={\'hosts\': \'localhost\'},
dev={\'hosts\': [\'esdev1.example.com:9200\'], sniff_on_start=True}
Connections... | def configure(self, **kwargs):
| for k in list(self._conns):
if ((k in self._kwargs) and (kwargs.get(k, None) == self._kwargs[k])):
continue
del self._conns[k]
self._kwargs = kwargs
|
'Add a connection object, it will be passed through as-is.'
| def add_connection(self, alias, conn):
| self._conns[alias] = conn
|
'Remove connection from the registry. Raises ``KeyError`` if connection
wasn\'t found.'
| def remove_connection(self, alias):
| errors = 0
for d in (self._conns, self._kwargs):
try:
del d[alias]
except KeyError:
errors += 1
if (errors == 2):
raise KeyError(('There is no connection with alias %r.' % alias))
|
'Construct an instance of ``elasticsearch.Elasticsearch`` and register
it under given alias.'
| def create_connection(self, alias='default', **kwargs):
| kwargs.setdefault('serializer', serializer)
conn = self._conns[alias] = Elasticsearch(**kwargs)
return conn
|
'Retrieve a connection, construct it if necessary (only configuration
was passed to us). If a non-string alias has been passed through we
assume it\'s already a client instance and will just return it as-is.
Raises ``KeyError`` if no client (or its definition) is registered
under the alias.'
| def get_connection(self, alias='default'):
| if (not isinstance(alias, string_types)):
return alias
try:
return self._conns[alias]
except KeyError:
pass
try:
return self.create_connection(alias, **self._kwargs[alias])
except KeyError:
raise KeyError(('There is no connection with alias %... |
'Execute an instruction based on it\'s type.'
| def run_code(self, test):
| for action in test:
self.assertEquals(1, len(action))
(action_type, action) = list(action.items())[0]
if hasattr(self, ('run_' + action_type)):
getattr(self, ('run_' + action_type))(action)
else:
raise InvalidActionType(action_type)
|
'Perform an api call with given parameters.'
| def run_do(self, action):
| api = self.client
if ('headers' in action):
api = self._get_client(headers=action.pop('headers'))
catch = action.pop('catch', None)
self.assertEquals(1, len(action))
(method, args) = list(action.items())[0]
for m in method.split('.'):
self.assertTrue(hasattr(api, m))
api ... |
':arg hosts: list of dictionaries, each containing keyword arguments to
create a `connection_class` instance
:arg connection_class: subclass of :class:`~elasticsearch.Connection` to use
:arg connection_pool_class: subclass of :class:`~elasticsearch.ConnectionPool` to use
:arg host_info_callback: callback responsible fo... | def __init__(self, hosts, connection_class=Urllib3HttpConnection, connection_pool_class=ConnectionPool, host_info_callback=get_host_info, sniff_on_start=False, sniffer_timeout=None, sniff_timeout=0.1, sniff_on_connection_fail=False, serializer=JSONSerializer(), serializers=None, default_mimetype='application/json', max... | _serializers = DEFAULT_SERIALIZERS.copy()
_serializers[serializer.mimetype] = serializer
if serializers:
_serializers.update(serializers)
self.deserializer = Deserializer(_serializers, default_mimetype)
self.max_retries = max_retries
self.retry_on_timeout = retry_on_timeout
self.retr... |
'Create a new :class:`~elasticsearch.Connection` instance and add it to the pool.
:arg host: kwargs that will be used to create the instance'
| def add_connection(self, host):
| self.hosts.append(host)
self.set_connections(self.hosts)
|
'Instantiate all the connections and crate new connection pool to hold
them. Tries to identify unchanged hosts and re-use existing
:class:`~elasticsearch.Connection` instances.
:arg hosts: same as `__init__`'
| def set_connections(self, hosts):
| def _create_connection(host):
if hasattr(self, 'connection_pool'):
for (connection, old_host) in self.connection_pool.connection_opts:
if (old_host == host):
return connection
kwargs = self.kwargs.copy()
kwargs.update(host)
return self.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.