INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Modify the given context in place based on the overwrite_context.
def apply_overwrites_to_context(context, overwrite_context): """Modify the given context in place based on the overwrite_context.""" for variable, overwrite in overwrite_context.items(): if variable not in context: # Do not include variables which are not used in the template con...
Generate the context for a Cookiecutter project template.
def generate_context(context_file='cookiecutter.json', default_context=None, extra_context=None): """Generate the context for a Cookiecutter project template. Loads the JSON file as a Python object, with key being the JSON filename. :param context_file: JSON file containing key/value ...
Render filename of infile as name of outfile handle infile correctly.
def generate_file(project_dir, infile, context, env): """Render filename of infile as name of outfile, handle infile correctly. Dealing with infile appropriately: a. If infile is a binary file, copy it over without rendering. b. If infile is a text file, render its contents and write the ...
Render name of a directory create the directory return its path.
def render_and_create_dir(dirname, context, output_dir, environment, overwrite_if_exists=False): """Render name of a directory, create the directory, return its path.""" name_tmpl = environment.from_string(dirname) rendered_dirname = name_tmpl.render(**context) dir_to_create =...
Run hook from repo directory clean project directory if hook fails.
def _run_hook_from_repo_dir(repo_dir, hook_name, project_dir, context, delete_project_on_failure): """Run hook from repo directory, clean project directory if hook fails. :param repo_dir: Project template input directory. :param hook_name: The hook to execute. :param project...
Render the templates and saves them to files.
def generate_files(repo_dir, context=None, output_dir='.', overwrite_if_exists=False): """Render the templates and saves them to files. :param repo_dir: Project template input directory. :param context: Dict for populating the template's variables. :param output_dir: Where to output ...
Expand both environment variables and user home in the given path.
def _expand_path(path): """Expand both environment variables and user home in the given path.""" path = os.path.expandvars(path) path = os.path.expanduser(path) return path
Recursively update a dict with the key/ value pair of another.
def merge_configs(default, overwrite): """Recursively update a dict with the key/value pair of another. Dict values that are dictionaries themselves will be updated, whilst preserving existing keys. """ new_config = copy.deepcopy(default) for k, v in overwrite.items(): # Make sure to p...
Retrieve the config from the specified path returning a config dict.
def get_config(config_path): """Retrieve the config from the specified path, returning a config dict.""" if not os.path.exists(config_path): raise ConfigDoesNotExistException logger.debug('config_path is {0}'.format(config_path)) with io.open(config_path, encoding='utf-8') as file_handle: ...
Return the user config as a dict.
def get_user_config(config_file=None, default_config=False): """Return the user config as a dict. If ``default_config`` is True, ignore ``config_file`` and return default values for the config parameters. If a path to a ``config_file`` is given, that is different from the default location, load th...
Error handler for shutil. rmtree () equivalent to rm - rf.
def force_delete(func, path, exc_info): """Error handler for `shutil.rmtree()` equivalent to `rm -rf`. Usage: `shutil.rmtree(path, onerror=force_delete)` From stackoverflow.com/questions/1889597 """ os.chmod(path, stat.S_IWRITE) func(path)
Ensure that a directory exists.
def make_sure_path_exists(path): """Ensure that a directory exists. :param path: A directory path. """ logger.debug('Making sure path exists: {}'.format(path)) try: os.makedirs(path) logger.debug('Created directory at: {}'.format(path)) except OSError as exception: if ex...
Context manager version of os. chdir.
def work_in(dirname=None): """Context manager version of os.chdir. When exited, returns to the working directory prior to entering. """ curdir = os.getcwd() try: if dirname is not None: os.chdir(dirname) yield finally: os.chdir(curdir)
Make script_path executable.
def make_executable(script_path): """Make `script_path` executable. :param script_path: The file to change """ status = os.stat(script_path) os.chmod(script_path, status.st_mode | stat.S_IEXEC)
Ask user if it s okay to delete the previously - downloaded file/ directory.
def prompt_and_delete(path, no_input=False): """ Ask user if it's okay to delete the previously-downloaded file/directory. If yes, delete it. If no, checks to see if the old version should be reused. If yes, it's reused; otherwise, Cookiecutter exits. :param path: Previously downloaded zipfile. ...
Download and unpack a zipfile at a given URI.
def unzip(zip_uri, is_url, clone_to_dir='.', no_input=False, password=None): """Download and unpack a zipfile at a given URI. This will download the zipfile to the cookiecutter repository, and unpack into a temporary directory. :param zip_uri: The URI for the zipfile. :param is_url: Is the zip URI...
Run Cookiecutter just as if using it from the command line.
def cookiecutter( template, checkout=None, no_input=False, extra_context=None, replay=False, overwrite_if_exists=False, output_dir='.', config_file=None, default_config=False, password=None): """ Run Cookiecutter just as if using it from the command line. :param template: A director...
Prompt the user to reply with yes or no ( or equivalent values ).
def read_user_yes_no(question, default_value): """Prompt the user to reply with 'yes' or 'no' (or equivalent values). Note: Possible choices are 'true', '1', 'yes', 'y' or 'false', '0', 'no', 'n' :param str question: Question to the user :param default_value: Value that will be returned if no in...
Prompt the user to choose from several options for the given variable.
def read_user_choice(var_name, options): """Prompt the user to choose from several options for the given variable. The first item will be returned if no input happens. :param str var_name: Variable as specified in the context :param list options: Sequence of options that are available to select from ...
Prompt the user to provide a dictionary of data.
def read_user_dict(var_name, default_value): """Prompt the user to provide a dictionary of data. :param str var_name: Variable as specified in the context :param default_value: Value that will be returned if no input is provided :return: A Python dictionary to use in the context. """ # Please s...
Inside the prompting taken from the cookiecutter. json file this renders the next variable. For example if a project_name is Peanut Butter Cookie the repo_name could be be rendered with:
def render_variable(env, raw, cookiecutter_dict): """Inside the prompting taken from the cookiecutter.json file, this renders the next variable. For example, if a project_name is "Peanut Butter Cookie", the repo_name could be be rendered with: `{{ cookiecutter.project_name.replace(" ", "_") }}`. ...
Prompt the user which option to choose from the given. Each of the possible choices is rendered beforehand.
def prompt_choice_for_config(cookiecutter_dict, env, key, options, no_input): """Prompt the user which option to choose from the given. Each of the possible choices is rendered beforehand. """ rendered_options = [ render_variable(env, raw, cookiecutter_dict) for raw in options ] if no_i...
Prompts the user to enter new config using context as a source for the field names and sample values.
def prompt_for_config(context, no_input=False): """ Prompts the user to enter new config, using context as a source for the field names and sample values. :param no_input: Prompt the user at command line for manual configuration? """ cookiecutter_dict = OrderedDict([]) env = StrictEnvironme...
Return list of extensions as str to be passed on to the Jinja2 env.
def _read_extensions(self, context): """Return list of extensions as str to be passed on to the Jinja2 env. If context does not contain the relevant info, return an empty list instead. """ try: extensions = context['cookiecutter']['_extensions'] except KeyErr...
Configure logging for cookiecutter.
def configure_logger(stream_level='DEBUG', debug_file=None): """Configure logging for cookiecutter. Set up logging to stdout with given level. If ``debug_file`` is given set up logging to file with DEBUG level. """ # Set up 'cookiecutter' logger logger = logging.getLogger('cookiecutter') lo...
Determine if repo_url should be treated as a URL to a git or hg repo.
def identify_repo(repo_url): """Determine if `repo_url` should be treated as a URL to a git or hg repo. Repos can be identified by prepending "hg+" or "git+" to the repo URL. :param repo_url: Repo URL of unknown type. :returns: ('git', repo_url), ('hg', repo_url), or None. """ repo_url_values ...
Clone a repo to the current directory.
def clone(repo_url, checkout=None, clone_to_dir='.', no_input=False): """Clone a repo to the current directory. :param repo_url: Repo URL of unknown type. :param checkout: The branch, tag or commit ID to checkout after clone. :param clone_to_dir: The directory to clone to. Defa...
Determine if a hook file is valid.
def valid_hook(hook_file, hook_name): """Determine if a hook file is valid. :param hook_file: The hook file to consider for validity :param hook_name: The hook to find :return: The hook file validity """ filename = os.path.basename(hook_file) basename = os.path.splitext(filename)[0] ma...
Return a dict of all hook scripts provided.
def find_hook(hook_name, hooks_dir='hooks'): """Return a dict of all hook scripts provided. Must be called with the project template as the current working directory. Dict's key will be the hook/script's name, without extension, while values will be the absolute path to the script. Missing scripts will...
Execute a script from a working directory.
def run_script(script_path, cwd='.'): """Execute a script from a working directory. :param script_path: Absolute path to the script to run. :param cwd: The directory to run the script from. """ run_thru_shell = sys.platform.startswith('win') if script_path.endswith('.py'): script_comman...
Execute a script after rendering it with Jinja.
def run_script_with_context(script_path, cwd, context): """Execute a script after rendering it with Jinja. :param script_path: Absolute path to the script to run. :param cwd: The directory to run the script from. :param context: Cookiecutter project template context. """ _, extension = os.path....
Try to find and execute a hook from the specified project directory.
def run_hook(hook_name, project_dir, context): """ Try to find and execute a hook from the specified project directory. :param hook_name: The hook to execute. :param project_dir: The directory to execute the script from. :param context: Cookiecutter project context. """ script = find_hook(h...
Return the Cookiecutter version location and Python powering it.
def version_msg(): """Return the Cookiecutter version, location and Python powering it.""" python_version = sys.version[:3] location = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) message = u'Cookiecutter %(version)s from {} (Python {})' return message.format(location, python_version)
Validate extra context.
def validate_extra_context(ctx, param, value): """Validate extra context.""" for s in value: if '=' not in s: raise click.BadParameter( 'EXTRA_CONTEXT should contain items of the form key=value; ' "'{}' doesn't match that form".format(s) ) # C...
Create a project from a Cookiecutter project template ( TEMPLATE ).
def main( template, extra_context, no_input, checkout, verbose, replay, overwrite_if_exists, output_dir, config_file, default_config, debug_file): """Create a project from a Cookiecutter project template (TEMPLATE). Cookiecutter is free and open source software, developed and managed by...
Mount the UnmountedType instance
def mounted(cls, unmounted): # noqa: N802 """ Mount the UnmountedType instance """ assert isinstance(unmounted, UnmountedType), ("{} can't mount {}").format( cls.__name__, repr(unmounted) ) return cls( unmounted.get_type(), *unmounted...
Creates a customized copy of the Parameter.
def replace( self, name=_void, kind=_void, annotation=_void, default=_void, _partial_kwarg=_void, ): """Creates a customized copy of the Parameter.""" if name is _void: name = self._name if kind is _void: kind = self._...
Constructs Signature for the given python function
def from_function(cls, func): """Constructs Signature for the given python function""" if not isinstance(func, types.FunctionType): raise TypeError("{!r} is not a Python function".format(func)) Parameter = cls._parameter_cls # Parameter information. func_code = fun...
Creates a customized copy of the Signature. Pass parameters and/ or return_annotation arguments to override them in the new copy.
def replace(self, parameters=_void, return_annotation=_void): """Creates a customized copy of the Signature. Pass 'parameters' and/or 'return_annotation' arguments to override them in the new copy. """ if parameters is _void: parameters = self.parameters.values() ...
Private method. Don t use directly.
def _bind(self, args, kwargs, partial=False): """Private method. Don't use directly.""" arguments = OrderedDict() parameters = iter(self.parameters.values()) parameters_ex = () arg_vals = iter(args) if partial: # Support for binding arguments to 'functools...
Get a BoundArguments object that partially maps the passed args and kwargs to the function s signature. Raises TypeError if the passed arguments can not be bound.
def bind_partial(self, *args, **kwargs): """Get a BoundArguments object, that partially maps the passed `args` and `kwargs` to the function's signature. Raises `TypeError` if the passed arguments can not be bound. """ return self._bind(args, kwargs, partial=True)
Check if the given objecttype has Node as an interface
def is_node(objecttype): """ Check if the given objecttype has Node as an interface """ if not isclass(objecttype): return False if not issubclass(objecttype, ObjectType): return False for i in objecttype._meta.interfaces: if issubclass(i, Node): return True...
Returns a tuple of the graphene version. If version argument is non - empty then checks for correctness of the tuple provided.
def get_complete_version(version=None): """Returns a tuple of the graphene version. If version argument is non-empty, then checks for correctness of the tuple provided. """ if version is None: from graphene import VERSION as version else: assert len(version) == 5 assert versi...
Execute a on_resolve function once the thenable is resolved returning the same type of object inputed. If the object is not thenable it should return on_resolve ( obj )
def maybe_thenable(obj, on_resolve): """ Execute a on_resolve function once the thenable is resolved, returning the same type of object inputed. If the object is not thenable, it should return on_resolve(obj) """ if isawaitable(obj) and not isinstance(obj, Promise): return await_and_exec...
Get type mounted
def get_field_as(value, _as=None): """ Get type mounted """ if isinstance(value, MountedType): return value elif isinstance(value, UnmountedType): if _as is None: return value return _as.mounted(value)
Extract all the fields in given attributes ( dict ) and return them ordered
def yank_fields_from_attrs(attrs, _as=None, sort=True): """ Extract all the fields in given attributes (dict) and return them ordered """ fields_with_names = [] for attname, value in list(attrs.items()): field = get_field_as(value, _as) if not field: continue ...
Import a dotted module path and return the attribute/ class designated by the last name in the path. When a dotted attribute path is also provided the dotted attribute path would be applied to the attribute/ class retrieved from the first step and return the corresponding value designated by the attribute path. Raise I...
def import_string(dotted_path, dotted_attributes=None): """ Import a dotted module path and return the attribute/class designated by the last name in the path. When a dotted attribute path is also provided, the dotted attribute path would be applied to the attribute/class retrieved from the first st...
Helper function used to iterate over all possible bucket combinations of source_aggs returning results of inner_aggs for each. Uses the composite aggregation under the hood to perform this.
def scan_aggs(search, source_aggs, inner_aggs={}, size=10): """ Helper function used to iterate over all possible bucket combinations of ``source_aggs``, returning results of ``inner_aggs`` for each. Uses the ``composite`` aggregation under the hood to perform this. """ def run_search(**kwargs):...
Automatically construct the suggestion input and weight by taking all possible permutation of Person s name as input and taking their popularity as weight.
def clean(self): """ Automatically construct the suggestion input and weight by taking all possible permutation of Person's name as ``input`` and taking their popularity as ``weight``. """ self.suggest = { 'input': [' '.join(p) for p in permutations(self.name....
Get all the fields defined for our class if we have an Index try looking at the index mappings as well mark the fields from Index as optional.
def __list_fields(cls): """ Get all the fields defined for our class, if we have an Index, try looking at the index mappings as well, mark the fields from Index as optional. """ for name in cls._doc_type.mapping: field = cls._doc_type.mapping[name] ...
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 internally by most state modifying APIs. """ ubq = super(UpdateByQuery, self)._clone() ubq._response_class = self._response_class ...
Override the default wrapper used for the response.
def response_class(self, cls): """ Override the default wrapper used for the response. """ ubq = self._clone() ubq._response_class = cls return ubq
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``. """ d = d.copy() if 'query' in d: self.query._proxied = Q(d.pop('query')) if 'script' in d: ...
Define update action to take: https:// www. elastic. co/ guide/ en/ elasticsearch/ reference/ current/ modules - scripting - using. html for more details.
def script(self, **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. ...
Serialize the search into the dictionary that will be sent over as the request ubq body.
def to_dict(self, **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. """ d = {} if self.query: d["query"] = self.query.to_dict(...
Execute the search and return an instance of Response wrapping all the data.
def execute(self): """ Execute the search and return an instance of ``Response`` wrapping all the data. """ es = connections.get_connection(self._using) self._response = self._response_class( self, es.update_by_query( index=self._i...
Iterate over all Field objects within including multi fields.
def _collect_fields(self): """ Iterate over all Field objects within, including multi fields. """ for f in itervalues(self.properties.to_dict()): yield f # multi fields if hasattr(f, 'fields'): for inner_f in itervalues(f.fields.to_dict()): ...
Create a copy of the instance with another name or connection alias. Useful for creating multiple indices with shared configuration::
def clone(self, 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...
Associate a: class: ~elasticsearch_dsl. 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::
def document(self, document): """ Associate a :class:`~elasticsearch_dsl.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 ``cla...
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.
def analyzer(self, *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_analyze...
Return a: class: ~elasticsearch_dsl. Search object searching over the index ( or all the indices belonging to this template ) and its Document \\ s.
def search(self, using=None): """ Return a :class:`~elasticsearch_dsl.Search` object searching over the index (or all the indices belonging to this template) and its ``Document``\\s. """ return Search( using=using or self._using, index=self._name, ...
Return a: class: ~elasticsearch_dsl. UpdateByQuery object searching over the index ( or all the indices belonging to this template ) and updating Documents that match the search criteria.
def updateByQuery(self, using=None): """ Return a :class:`~elasticsearch_dsl.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....
Creates the index in elasticsearch.
def create(self, using=None, **kwargs): """ Creates the index in elasticsearch. Any additional keyword arguments will be passed to ``Elasticsearch.indices.create`` unchanged. """ self._get_connection(using).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.
def save(self, 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...
Perform the analysis process on a text and return the tokens breakdown of the text.
def analyze(self, 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. """ return self._get_connection(using)...
Preforms a refresh operation on the index.
def refresh(self, using=None, **kwargs): """ Preforms a refresh operation on the index. Any additional keyword arguments will be passed to ``Elasticsearch.indices.refresh`` unchanged. """ return self._get_connection(using).indices.refresh(index=self._name, **kwargs)
Preforms a flush operation on the index.
def flush(self, using=None, **kwargs): """ Preforms a flush operation on the index. Any additional keyword arguments will be passed to ``Elasticsearch.indices.flush`` unchanged. """ return self._get_connection(using).indices.flush(index=self._name, **kwargs)
The get index API allows to retrieve information about the index.
def get(self, 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. """ return self._get_connection(using).indices.get(index=self._name, **k...
Opens the index in elasticsearch.
def open(self, using=None, **kwargs): """ Opens the index in elasticsearch. Any additional keyword arguments will be passed to ``Elasticsearch.indices.open`` unchanged. """ return self._get_connection(using).indices.open(index=self._name, **kwargs)
Closes the index in elasticsearch.
def close(self, using=None, **kwargs): """ Closes the index in elasticsearch. Any additional keyword arguments will be passed to ``Elasticsearch.indices.close`` unchanged. """ return self._get_connection(using).indices.close(index=self._name, **kwargs)
Deletes the index in elasticsearch.
def delete(self, using=None, **kwargs): """ Deletes the index in elasticsearch. Any additional keyword arguments will be passed to ``Elasticsearch.indices.delete`` unchanged. """ return self._get_connection(using).indices.delete(index=self._name, **kwargs)
Returns True if the index already exists in elasticsearch.
def exists(self, using=None, **kwargs): """ Returns ``True`` if the index already exists in elasticsearch. Any additional keyword arguments will be passed to ``Elasticsearch.indices.exists`` unchanged. """ return self._get_connection(using).indices.exists(index=self._nam...
Check if a type/ types exists in the index.
def exists_type(self, using=None, **kwargs): """ Check if a type/types exists in the index. Any additional keyword arguments will be passed to ``Elasticsearch.indices.exists_type`` unchanged. """ return self._get_connection(using).indices.exists_type(index=self._name, **...
Register specific mapping definition for a specific type.
def put_mapping(self, using=None, **kwargs): """ Register specific mapping definition for a specific type. Any additional keyword arguments will be passed to ``Elasticsearch.indices.put_mapping`` unchanged. """ return self._get_connection(using).indices.put_mapping(index...
Retrieve specific mapping definition for a specific type.
def get_mapping(self, using=None, **kwargs): """ Retrieve specific mapping definition for a specific type. Any additional keyword arguments will be passed to ``Elasticsearch.indices.get_mapping`` unchanged. """ return self._get_connection(using).indices.get_mapping(index...
Retrieve mapping definition of a specific field.
def get_field_mapping(self, using=None, **kwargs): """ Retrieve mapping definition of a specific field. Any additional keyword arguments will be passed to ``Elasticsearch.indices.get_field_mapping`` unchanged. """ return self._get_connection(using).indices.get_field_mapp...
Create an alias for the index.
def put_alias(self, using=None, **kwargs): """ Create an alias for the index. Any additional keyword arguments will be passed to ``Elasticsearch.indices.put_alias`` unchanged. """ return self._get_connection(using).indices.put_alias(index=self._name, **kwargs)
Return a boolean indicating whether given alias exists for this index.
def exists_alias(self, 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. """ return self._get_connection(using).indices.ex...
Retrieve a specified alias.
def get_alias(self, using=None, **kwargs): """ Retrieve a specified alias. Any additional keyword arguments will be passed to ``Elasticsearch.indices.get_alias`` unchanged. """ return self._get_connection(using).indices.get_alias(index=self._name, **kwargs)
Delete specific alias.
def delete_alias(self, using=None, **kwargs): """ Delete specific alias. Any additional keyword arguments will be passed to ``Elasticsearch.indices.delete_alias`` unchanged. """ return self._get_connection(using).indices.delete_alias(index=self._name, **kwargs)
Retrieve settings for the index.
def get_settings(self, using=None, **kwargs): """ Retrieve settings for the index. Any additional keyword arguments will be passed to ``Elasticsearch.indices.get_settings`` unchanged. """ return self._get_connection(using).indices.get_settings(index=self._name, **kwargs)
Change specific index level settings in real time.
def put_settings(self, using=None, **kwargs): """ Change specific index level settings in real time. Any additional keyword arguments will be passed to ``Elasticsearch.indices.put_settings`` unchanged. """ return self._get_connection(using).indices.put_settings(index=sel...
Retrieve statistics on different operations happening on the index.
def stats(self, using=None, **kwargs): """ Retrieve statistics on different operations happening on the index. Any additional keyword arguments will be passed to ``Elasticsearch.indices.stats`` unchanged. """ return self._get_connection(using).indices.stats(index=self._n...
Provide low level segments information that a Lucene index ( shard level ) is built with.
def segments(self, 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. """ return self._get_connection(...
Validate a potentially expensive query without executing it.
def validate_query(self, using=None, **kwargs): """ Validate a potentially expensive query without executing it. Any additional keyword arguments will be passed to ``Elasticsearch.indices.validate_query`` unchanged. """ return self._get_connection(using).indices.validate...
Clear all caches or specific cached associated with the index.
def clear_cache(self, 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. """ return self._get_connection(using).indices.clear_cache(...
The indices recovery API provides insight into on - going shard recoveries for the index.
def recovery(self, 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. """ return self._get_connection(...
Upgrade the index to the latest format.
def upgrade(self, using=None, **kwargs): """ Upgrade the index to the latest format. Any additional keyword arguments will be passed to ``Elasticsearch.indices.upgrade`` unchanged. """ return self._get_connection(using).indices.upgrade(index=self._name, **kwargs)
Monitor how much of the index is upgraded.
def get_upgrade(self, using=None, **kwargs): """ Monitor how much of the index is upgraded. Any additional keyword arguments will be passed to ``Elasticsearch.indices.get_upgrade`` unchanged. """ return self._get_connection(using).indices.get_upgrade(index=self._name, **...
Perform a normal flush then add a generated unique marker ( sync_id ) to all shards.
def flush_synced(self, using=None, **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. """ return self._get_connect...
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.
def shard_stores(self, 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 ...
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.
def forcemerge(self, 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 mergin...
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 s...
def shrink(self, 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 pri...
Configure multiple connections at once useful for passing in config dictionaries obtained from other sources like Django s settings or a configuration management tool.
def configure(self, **kwargs): """ 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={'ho...
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): try: del d[alias] except KeyError: err...
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('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.
def get_connection(self, alias='default'): """ 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 ...
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, ideally at every new code deploy. """ # create an index template index_template = BlogPost._index.as_template(ALIAS, PATTERN) # upload the templat...
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 ).
def migrate(move_data=True, update_alias=True): """ 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 in...
Use the Analyze API of elasticsearch to test the outcome of this analyzer.
def simulate(self, text, using='default', explain=False, attributes=None): """ 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 t...