text
stringlengths
81
112k
Create an alias for the index. Any additional keyword arguments will be passed to ``Elasticsearch.indices.put_alias`` unchanged. def put_alias(self, using=None, **kwargs): """ Create an alias for the index. Any additional keyword arguments will be passed to ``Elasticse...
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, using=None, **kwargs): """ Return a boolean indicating whether given alias exists for this ...
Retrieve a specified alias. Any additional keyword arguments will be passed to ``Elasticsearch.indices.get_alias`` unchanged. def get_alias(self, using=None, **kwargs): """ Retrieve a specified alias. Any additional keyword arguments will be passed to ``Elasticsearch.i...
Delete specific alias. Any additional keyword arguments will be passed to ``Elasticsearch.indices.delete_alias`` unchanged. def delete_alias(self, using=None, **kwargs): """ Delete specific alias. Any additional keyword arguments will be passed to ``Elasticsearch.indic...
Retrieve settings for the index. Any additional keyword arguments will be passed to ``Elasticsearch.indices.get_settings`` unchanged. def get_settings(self, using=None, **kwargs): """ Retrieve settings for the index. Any additional keyword arguments will be passed to `...
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, using=None, **kwargs): """ Change specific index level settings in real time. Any additional keyword a...
Retrieve statistics on different operations happening on the index. Any additional keyword arguments will be passed to ``Elasticsearch.indices.stats`` unchanged. def stats(self, using=None, **kwargs): """ Retrieve statistics on different operations happening on the index. Any ...
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, using=None, **kwargs): """ Provide low level segments information that a L...
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, using=None, **kwargs): """ Validate a potentially expensive query without executing it. ...
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, using=None, **kwargs): """ Clear all caches or specific cached associated with the index. An...
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, using=None, **kwargs): """ The indices recovery API provides insight into ...
Upgrade the index to the latest format. Any additional keyword arguments will be passed to ``Elasticsearch.indices.upgrade`` unchanged. def upgrade(self, using=None, **kwargs): """ Upgrade the index to the latest format. Any additional keyword arguments will be passed to ...
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, using=None, **kwargs): """ Monitor how much of the index is upgraded. Any additional keyword arguments will be p...
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, using=None, **kwargs): """ Perform a normal flush, then add a generate...
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 keyw...
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 complet...
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 sha...
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': [...
Remove connection from the registry. Raises ``KeyError`` if connection wasn't found. def remove_connection(self, alias): """ Remove connection from the registry. Raises ``KeyError`` if connection wasn't found. """ errors = 0 for d in (self._conns, self._kwargs): ...
Construct an instance of ``elasticsearch.Elasticsearch`` and register it under given alias. def create_connection(self, alias='default', **kwargs): """ Construct an instance of ``elasticsearch.Elasticsearch`` and register it under given alias. """ kwargs.setdefault('seri...
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 alia...
Create the index template in elasticsearch specifying the mappings and any settings to be used. This can be run at any time, ideally at every new code deploy. def setup(): """ Create the index template in elasticsearch specifying the mappings and any settings to be used. This can be run at any time...
Upgrade function that creates a new index for the data. Optionally it also can (and by default will) reindex previous copy of the data into the new index (specify ``move_data=False`` to skip this step) and update the alias to point to the latest index (set ``update_alias=False`` to skip). Note that whi...
Use the Analyze API of elasticsearch to test the outcome of this analyzer. :arg text: Text to be analyzed :arg using: connection alias to use, defaults to ``'default'`` :arg explain: will output all token attributes for each token. You can filter token attributes you want to output ...
Get answers either from inner_hits already present or by searching elasticsearch. def get_answers(self): """ Get answers either from inner_hits already present or by searching elasticsearch. """ if 'inner_hits' in self.meta and 'answer' in self.meta.inner_hits: ...
Return the aggregation object. def get_aggregation(self): """ Return the aggregation object. """ agg = A(self.agg_type, **self._params) if self._metric: agg.metric('metric', self._metric) return agg
Construct a filter. def add_filter(self, filter_values): """ Construct a filter. """ 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
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): """ Turn the raw bucket data into a list of tuples containing the key, number of d...
Add a filter for a facet. def add_filter(self, name, filter_values): """ Add a filter for a facet. """ # normalize the value into a list if not isinstance(filter_values, (tuple, list)): if filter_values is None: return filter_values = [fil...
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. def search(self): """ Returns the base Search object to which the facets are added. You can customize the query by overri...
Add query part to ``search``. Override this if you wish to customize the query used. def query(self, search, query): """ Add query part to ``search``. Override this if you wish to customize the query used. """ if query: if self.fields: retur...
Add aggregations representing the facets selected, including potential filters. def aggregate(self, search): """ Add aggregations representing the facets selected, including potential filters. """ for f, facet in iteritems(self.facets): agg = facet.get_aggreg...
Add a ``post_filter`` to the search request narrowing the results based on the facet filters. def filter(self, search): """ Add a ``post_filter`` to the search request narrowing the results based on the facet filters. """ if not self._filters: return search ...
Add highlighting for all the fields def highlight(self, search): """ Add highlighting for all the fields """ 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): """ Add sorting information to the request. """ if self._sort: search = search.sort(*self._sort) return search
Construct the ``Search`` object. def build_search(self): """ Construct the ``Search`` object. """ s = self.search() s = self.query(s, self._query) s = self.filter(s) if self.fields: s = self.highlight(s) s = self.sort(s) self.aggregate...
Execute the search and return the response. def execute(self): """ Execute the search and return the response. """ r = self._s.execute() r._faceted_search = self return r
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() ...
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): """ Set the index ...
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 info...
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): ...
Add extra keys to the request body. Mostly here for backwards compatibility. def extra(self, **kwargs): """ Add extra keys to the request body. Mostly here for backwards compatibility. """ s = self._clone() if 'from_' in kwargs: kwargs['from'] = kwarg...
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): """ Return a clone of the current search request. Performs a shallow copy of all the underlying objects. Used inte...
Override the default wrapper used for the response. def response_class(self, cls): """ Override the default wrapper used for the response. """ 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): """ Apply options from a serialized body to the current instance. Modifies the object in-place. Used mostly by ``from_dict``. ...
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...
Selectively control how the _source field is returned. :arg fields: wildcard string, array of wildcards, or dictionary of includes and excludes If ``fields`` is None, the entire document will be returned for each hit. If fields is a dictionary with keys of 'include' and/or 'exclude' t...
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::...
Update the global highlighting options used for this request. For example:: s = Search() s = s.highlight_options(order='score') def highlight_options(self, **kwargs): """ Update the global highlighting options used for this request. For example:: 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": { ...
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 ...
Serialize the search into the dictionary that will be sent over as the request's body. :arg count: a flag to specify if 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_...
Return the number of hits matching the query and filters. Note that only the actual number is returned. def count(self): """ Return the number of hits matching the query and filters. Note that only the actual number is returned. """ if hasattr(self, '_response'): ...
Execute the search and return an instance of ``Response`` wrapping all the data. :arg ignore_cache: if set to ``True``, consecutive calls will hit ES, while cached result will be ignored. Defaults to `False` def execute(self, ignore_cache=False): """ Execute the search and ...
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.readth...
delete() executes the query by delegating to delete_by_query() def delete(self): """ delete() executes the query by delegating to delete_by_query() """ es = connections.get_connection(self._using) return AttrDict( es.delete_by_query( index=self._ind...
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): """ Adds a new :class:`~elasti...
Execute the multi search request and return a list of search results. def execute(self, ignore_cache=False, raise_on_error=True): """ Execute the multi search request and return a list of search results. """ if ignore_cache or not hasattr(self, '_response'): es = connections...
Create a tar file from all the files under 'base_dir'. This file may be compressed. :param compress: Compression algorithms. Supported algorithms are: 'gzip': (the default) 'compress' 'bzip2' None For 'gzip' and 'bzip2' the internal tarfile module will be used. For 'comp...
Start the GSS-API / SSPI Authenticated Diffie-Hellman Key Exchange. def start_kex(self): """ Start the GSS-API / SSPI Authenticated Diffie-Hellman Key Exchange. """ self._generate_x() if self.transport.server_mode: # compute f = g^x mod p, but don't send it yet ...
Parse the next packet. :param ptype: The (string) type of the incoming packet :param `.Message` m: The paket content def parse_next(self, ptype, m): """ Parse the next packet. :param ptype: The (string) type of the incoming packet :param `.Message` m: The paket content...
Parse the SSH2_MSG_KEXGSS_HOSTKEY message (client mode). :param `.Message` m: The content of the SSH2_MSG_KEXGSS_HOSTKEY message def _parse_kexgss_hostkey(self, m): """ Parse the SSH2_MSG_KEXGSS_HOSTKEY message (client mode). :param `.Message` m: The content of the SSH2_MSG_KEXGSS_HOS...
Parse the SSH2_MSG_KEXGSS_CONTINUE message. :param `.Message` m: The content of the SSH2_MSG_KEXGSS_CONTINUE message def _parse_kexgss_continue(self, m): """ Parse the SSH2_MSG_KEXGSS_CONTINUE message. :param `.Message` m: The content of the SSH2_MSG_KEXGSS_CONTINUE ...
Parse the SSH2_MSG_KEXGSS_COMPLETE message (client mode). :param `.Message` m: The content of the SSH2_MSG_KEXGSS_COMPLETE message def _parse_kexgss_complete(self, m): """ Parse the SSH2_MSG_KEXGSS_COMPLETE message (client mode). :param `.Message` m: The content of the ...
Parse the SSH2_MSG_KEXGSS_INIT message (server mode). :param `.Message` m: The content of the SSH2_MSG_KEXGSS_INIT message def _parse_kexgss_init(self, m): """ Parse the SSH2_MSG_KEXGSS_INIT message (server mode). :param `.Message` m: The content of the SSH2_MSG_KEXGSS_INIT message ...
Start the GSS-API / SSPI Authenticated Diffie-Hellman Group Exchange def start_kex(self): """ Start the GSS-API / SSPI Authenticated Diffie-Hellman Group Exchange """ if self.transport.server_mode: self.transport._expect_packet(MSG_KEXGSS_GROUPREQ) return ...
Parse the next packet. :param ptype: The (string) type of the incoming packet :param `.Message` m: The paket content def parse_next(self, ptype, m): """ Parse the next packet. :param ptype: The (string) type of the incoming packet :param `.Message` m: The paket content...
Parse the SSH2_MSG_KEXGSS_GROUP message (client mode). :param `Message` m: The content of the SSH2_MSG_KEXGSS_GROUP message def _parse_kexgss_group(self, m): """ Parse the SSH2_MSG_KEXGSS_GROUP message (client mode). :param `Message` m: The content of the SSH2_MSG_KEXGSS_GROUP message...
Parse the SSH2_MSG_KEXGSS_COMPLETE message (client mode). :param `Message` m: The content of the SSH2_MSG_KEXGSS_COMPLETE message def _parse_kexgss_complete(self, m): """ Parse the SSH2_MSG_KEXGSS_COMPLETE message (client mode). :param `Message` m: The content of the SSH2_MSG_KEXGSS_C...
Parse the SSH2_MSG_KEXGSS_ERROR message (client mode). The server may send a GSS-API error message. if it does, we display the error by throwing an exception (client mode). :param `Message` m: The content of the SSH2_MSG_KEXGSS_ERROR message :raise SSHException: Contains GSS-API major ...
Create an `.SFTPAttributes` object from an existing ``stat`` object (an object returned by `os.stat`). :param object obj: an object returned by `os.stat` (or equivalent). :param str filename: the filename associated with this file. :return: new `.SFTPAttributes` object with the same att...
Generate a new private RSA key. This factory function can be used to generate a new host key or authentication key. :param int bits: number of bits the generated key should be. :param progress_func: Unused :return: new `.RSAKey` private key def generate(bits, progress_func=None): ...
if a block of data is present in the prefetch buffers, at the given offset, return the offset of the relevant prefetch buffer. otherwise, return None. this guarantees nothing about the number of bytes collected in the prefetch buffer so far. def _data_in_prefetch_buffers(self, offset): ...
Set the file's current position. See `file.seek` for details. def seek(self, offset, whence=0): """ Set the file's current position. See `file.seek` for details. """ self.flush() if whence == self.SEEK_SET: self._realpos = self._pos = offset ...
Retrieve information about this file from the remote system. This is exactly like `.SFTPClient.stat`, except that it operates on an already-open file. :returns: an `.SFTPAttributes` object containing attributes about this file. def stat(self): """ Retrieve informat...
Change the size of this file. This usually extends or shrinks the size of the file, just like the ``truncate()`` method on Python file objects. :param size: the new size of the file def truncate(self, size): """ Change the size of this file. This usually extends or sh...
Ask the server for a hash of a section of this file. This can be used to verify a successful upload or download, or for various rsync-like operations. The file is hashed from ``offset``, for ``length`` bytes. If ``length`` is 0, the remainder of the file is hashed. Thus, if both ...
Pre-fetch the remaining contents of this file in anticipation of future `.read` calls. If reading the entire file, pre-fetching can dramatically improve the download speed by avoiding roundtrip latency. The file's contents are incrementally buffered in a background thread. The prefetch...
Read a set of blocks from the file by (offset, length). This is more efficient than doing a series of `.seek` and `.read` calls, since the prefetch machinery is used to retrieve all the requested blocks at once. :param chunks: a list of ``(offset, length)`` tuples indicatin...
if there's a saved exception, raise & clear it def _check_exception(self): """if there's a saved exception, raise & clear it""" if self._saved_exception is not None: x = self._saved_exception self._saved_exception = None raise x
Decorator for `.Channel` methods which performs an openness check. :raises: `.SSHException` -- If the wrapped method is called on an unopened `.Channel`. def open_only(func): """ Decorator for `.Channel` methods which performs an openness check. :raises: `.SSHException` -- If ...
Execute a command on the server. If the server allows it, the channel will then be directly connected to the stdin, stdout, and stderr of the command being executed. When the command finishes executing, the channel will be closed and can't be reused. You must open a new channel if you...
Resize the pseudo-terminal. This can be used to change the width and height of the terminal emulation created in a previous `get_pty` call. :param int width: new width (in characters) of the terminal screen :param int height: new height (in characters) of the terminal screen :param int...
Updates this channel's remote shell environment. .. note:: This operation is additive - i.e. the current environment is not reset before the given environment variables are set. .. warning:: Servers may silently reject some environment variables; see the ...
Set the value of an environment variable. .. warning:: The server may reject this request depending on its ``AcceptEnv`` setting; such rejections will fail silently (which is common client practice for this particular request type). Make sure you understand your ...
Return the exit status from the process on the server. This is mostly useful for retrieving the results of an `exec_command`. If the command hasn't finished yet, this method will wait until it does, or until the channel is closed. If no exit status is provided by the server, -1 is retu...
Request an x11 session on this channel. If the server allows it, further x11 requests can be made from the server to the client, when an x11 application is run in a shell session. From :rfc:`4254`:: It is RECOMMENDED that the 'x11 authentication cookie' that is sent be...
Request for a forward SSH Agent on this channel. This is only valid for an ssh-agent from OpenSSH !!! :param handler: a required callable handler to use for incoming SSH Agent connections :return: True if we are ok, else False (at that time we always return ...
Set whether stderr should be combined into stdout on this channel. The default is ``False``, but in some cases it may be convenient to have both streams combined. If this is ``False``, and `exec_command` is called (or ``invoke_shell`` with no pty), output to stderr will not show up thro...
Close the channel. All future read/write operations on the channel will fail. The remote end will receive no more data (after queued data is flushed). Channels are automatically closed when their `.Transport` is closed or when they are garbage collected. def close(self): """ ...
Returns true if data can be written to this channel without blocking. This means the channel is either closed (so any write attempt would return immediately) or there is at least one byte of space in the outbound buffer. If there is at least one byte of space in the outbound buffer, a `s...
Send data to the channel. Returns the number of bytes sent, or 0 if the channel stream is closed. Applications are responsible for checking that all data has been sent: if only some of the data was transmitted, the application needs to attempt delivery of the remaining data. :...
Send data to the channel on the "stderr" stream. This is normally only used by servers to send output from shell commands -- clients won't use this. Returns the number of bytes sent, or 0 if the channel stream is closed. Applications are responsible for checking that all data has been...
Send data to the channel, without allowing partial results. Unlike `send`, this method continues to send data from the given string until either all data has been sent or an error occurs. Nothing is returned. :param str s: data to send. :raises socket.timeout: if sending ...
Send data to the channel's "stderr" stream, without allowing partial results. Unlike `send_stderr`, this method continues to send data from the given string until all data has been sent or an error occurs. Nothing is returned. :param str s: data to send to the client as "stderr" output...
Returns an OS-level file descriptor which can be used for polling, but but not for reading or writing. This is primarily to allow Python's ``select`` module to work. The first time ``fileno`` is called on a channel, a pipe is created to simulate real OS-level file descriptor (FD) behav...
Shut down one or both halves of the connection. If ``how`` is 0, further receives are disallowed. If ``how`` is 1, further sends are disallowed. If ``how`` is 2, further sends and receives are disallowed. This closes the stream in one or both directions. :param int how: ...
(You are already holding the lock.) Wait for the send window to open up, and allocate up to ``size`` bytes for transmission. If no space opens up before the timeout, a timeout exception is raised. Returns the number of bytes available to send (may be less than requested). def _wait_fo...
Convert an errno value (as from an ``OSError`` or ``IOError``) into a standard SFTP result code. This is a convenience function for trapping exceptions in server code and returning an appropriate result. :param int e: an errno code, as from ``OSError.errno``. :return: an `int` SFTP err...
convert SFTP-style open() flags to Python's os.open() flags def _convert_pflags(self, pflags): """convert SFTP-style open() flags to Python's os.open() flags""" if (pflags & SFTP_FLAG_READ) and (pflags & SFTP_FLAG_WRITE): flags = os.O_RDWR elif pflags & SFTP_FLAG_WRITE: ...