repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
aparo/pyes | pyes/es.py | ES._check_servers | def _check_servers(self):
"""Check the servers variable and convert in a valid tuple form"""
new_servers = []
def check_format(server):
if server.scheme not in ["thrift", "http", "https"]:
raise RuntimeError("Unable to recognize protocol: \"%s\"" % _type)
if server.scheme == "thrift":
if not thrift_connect:
raise RuntimeError("If you want to use thrift, please install thrift. \"pip install thrift\"")
if server.port is None:
raise RuntimeError("If you want to use thrift, please provide a port number")
new_servers.append(server)
for server in self.servers:
if isinstance(server, (tuple, list)):
if len(list(server)) != 3:
raise RuntimeError("Invalid server definition: \"%s\"" % repr(server))
_type, host, port = server
server = urlparse('%s://%s:%s' % (_type, host, port))
check_format(server)
elif isinstance(server, six.string_types):
if server.startswith(("thrift:", "http:", "https:")):
server = urlparse(server)
check_format(server)
continue
else:
tokens = [t for t in server.split(":") if t.strip()]
if len(tokens) == 2:
host = tokens[0]
try:
port = int(tokens[1])
except ValueError:
raise RuntimeError("Invalid port: \"%s\"" % tokens[1])
if 9200 <= port <= 9299:
_type = "http"
elif 9500 <= port <= 9599:
_type = "thrift"
else:
raise RuntimeError("Unable to recognize port-type: \"%s\"" % port)
server = urlparse('%s://%s:%s' % (_type, host, port))
check_format(server)
self.servers = new_servers | python | def _check_servers(self):
"""Check the servers variable and convert in a valid tuple form"""
new_servers = []
def check_format(server):
if server.scheme not in ["thrift", "http", "https"]:
raise RuntimeError("Unable to recognize protocol: \"%s\"" % _type)
if server.scheme == "thrift":
if not thrift_connect:
raise RuntimeError("If you want to use thrift, please install thrift. \"pip install thrift\"")
if server.port is None:
raise RuntimeError("If you want to use thrift, please provide a port number")
new_servers.append(server)
for server in self.servers:
if isinstance(server, (tuple, list)):
if len(list(server)) != 3:
raise RuntimeError("Invalid server definition: \"%s\"" % repr(server))
_type, host, port = server
server = urlparse('%s://%s:%s' % (_type, host, port))
check_format(server)
elif isinstance(server, six.string_types):
if server.startswith(("thrift:", "http:", "https:")):
server = urlparse(server)
check_format(server)
continue
else:
tokens = [t for t in server.split(":") if t.strip()]
if len(tokens) == 2:
host = tokens[0]
try:
port = int(tokens[1])
except ValueError:
raise RuntimeError("Invalid port: \"%s\"" % tokens[1])
if 9200 <= port <= 9299:
_type = "http"
elif 9500 <= port <= 9599:
_type = "thrift"
else:
raise RuntimeError("Unable to recognize port-type: \"%s\"" % port)
server = urlparse('%s://%s:%s' % (_type, host, port))
check_format(server)
self.servers = new_servers | [
"def",
"_check_servers",
"(",
"self",
")",
":",
"new_servers",
"=",
"[",
"]",
"def",
"check_format",
"(",
"server",
")",
":",
"if",
"server",
".",
"scheme",
"not",
"in",
"[",
"\"thrift\"",
",",
"\"http\"",
",",
"\"https\"",
"]",
":",
"raise",
"RuntimeErr... | Check the servers variable and convert in a valid tuple form | [
"Check",
"the",
"servers",
"variable",
"and",
"convert",
"in",
"a",
"valid",
"tuple",
"form"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/es.py#L304-L351 | train | 29,300 |
aparo/pyes | pyes/es.py | ES._init_connection | def _init_connection(self):
"""
Create initial connection pool
"""
#detect connectiontype
if not self.servers:
raise RuntimeError("No server defined")
server = random.choice(self.servers)
if server.scheme in ["http", "https"]:
self.connection = http_connect(
[server for server in self.servers if server.scheme in ["http", "https"]],
timeout=self.timeout, basic_auth=self.basic_auth, max_retries=self.max_retries, retry_time=self.retry_time)
return
elif server.scheme == "thrift":
self.connection = thrift_connect(
[server for server in self.servers if server.scheme == "thrift"],
timeout=self.timeout, max_retries=self.max_retries, retry_time=self.retry_time) | python | def _init_connection(self):
"""
Create initial connection pool
"""
#detect connectiontype
if not self.servers:
raise RuntimeError("No server defined")
server = random.choice(self.servers)
if server.scheme in ["http", "https"]:
self.connection = http_connect(
[server for server in self.servers if server.scheme in ["http", "https"]],
timeout=self.timeout, basic_auth=self.basic_auth, max_retries=self.max_retries, retry_time=self.retry_time)
return
elif server.scheme == "thrift":
self.connection = thrift_connect(
[server for server in self.servers if server.scheme == "thrift"],
timeout=self.timeout, max_retries=self.max_retries, retry_time=self.retry_time) | [
"def",
"_init_connection",
"(",
"self",
")",
":",
"#detect connectiontype",
"if",
"not",
"self",
".",
"servers",
":",
"raise",
"RuntimeError",
"(",
"\"No server defined\"",
")",
"server",
"=",
"random",
".",
"choice",
"(",
"self",
".",
"servers",
")",
"if",
... | Create initial connection pool | [
"Create",
"initial",
"connection",
"pool"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/es.py#L353-L370 | train | 29,301 |
aparo/pyes | pyes/es.py | ES._discovery | def _discovery(self):
"""
Find other servers asking nodes to given server
"""
data = self.cluster_nodes()
self.cluster_name = data["cluster_name"]
for _, nodedata in list(data["nodes"].items()):
server = nodedata['http_address'].replace("]", "").replace("inet[", "http:/")
if server not in self.servers:
self.servers.append(server)
self._init_connection()
return self.servers | python | def _discovery(self):
"""
Find other servers asking nodes to given server
"""
data = self.cluster_nodes()
self.cluster_name = data["cluster_name"]
for _, nodedata in list(data["nodes"].items()):
server = nodedata['http_address'].replace("]", "").replace("inet[", "http:/")
if server not in self.servers:
self.servers.append(server)
self._init_connection()
return self.servers | [
"def",
"_discovery",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"cluster_nodes",
"(",
")",
"self",
".",
"cluster_name",
"=",
"data",
"[",
"\"cluster_name\"",
"]",
"for",
"_",
",",
"nodedata",
"in",
"list",
"(",
"data",
"[",
"\"nodes\"",
"]",
".",... | Find other servers asking nodes to given server | [
"Find",
"other",
"servers",
"asking",
"nodes",
"to",
"given",
"server"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/es.py#L372-L383 | train | 29,302 |
aparo/pyes | pyes/es.py | ES._set_bulk_size | def _set_bulk_size(self, bulk_size):
"""
Set the bulk size
:param bulk_size the bulker size
"""
self._bulk_size = bulk_size
self.bulker.bulk_size = bulk_size | python | def _set_bulk_size(self, bulk_size):
"""
Set the bulk size
:param bulk_size the bulker size
"""
self._bulk_size = bulk_size
self.bulker.bulk_size = bulk_size | [
"def",
"_set_bulk_size",
"(",
"self",
",",
"bulk_size",
")",
":",
"self",
".",
"_bulk_size",
"=",
"bulk_size",
"self",
".",
"bulker",
".",
"bulk_size",
"=",
"bulk_size"
] | Set the bulk size
:param bulk_size the bulker size | [
"Set",
"the",
"bulk",
"size"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/es.py#L393-L400 | train | 29,303 |
aparo/pyes | pyes/es.py | ES._set_raise_on_bulk_item_failure | def _set_raise_on_bulk_item_failure(self, raise_on_bulk_item_failure):
"""
Set the raise_on_bulk_item_failure parameter
:param raise_on_bulk_item_failure a bool the status of the raise_on_bulk_item_failure
"""
self._raise_on_bulk_item_failure = raise_on_bulk_item_failure
self.bulker.raise_on_bulk_item_failure = raise_on_bulk_item_failure | python | def _set_raise_on_bulk_item_failure(self, raise_on_bulk_item_failure):
"""
Set the raise_on_bulk_item_failure parameter
:param raise_on_bulk_item_failure a bool the status of the raise_on_bulk_item_failure
"""
self._raise_on_bulk_item_failure = raise_on_bulk_item_failure
self.bulker.raise_on_bulk_item_failure = raise_on_bulk_item_failure | [
"def",
"_set_raise_on_bulk_item_failure",
"(",
"self",
",",
"raise_on_bulk_item_failure",
")",
":",
"self",
".",
"_raise_on_bulk_item_failure",
"=",
"raise_on_bulk_item_failure",
"self",
".",
"bulker",
".",
"raise_on_bulk_item_failure",
"=",
"raise_on_bulk_item_failure"
] | Set the raise_on_bulk_item_failure parameter
:param raise_on_bulk_item_failure a bool the status of the raise_on_bulk_item_failure | [
"Set",
"the",
"raise_on_bulk_item_failure",
"parameter"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/es.py#L412-L419 | train | 29,304 |
aparo/pyes | pyes/es.py | ES._validate_indices | def _validate_indices(self, indices=None):
"""Return a valid list of indices.
`indices` may be a string or a list of strings.
If `indices` is not supplied, returns the default_indices.
"""
if indices is None:
indices = self.default_indices
if isinstance(indices, six.string_types):
indices = [indices]
return indices | python | def _validate_indices(self, indices=None):
"""Return a valid list of indices.
`indices` may be a string or a list of strings.
If `indices` is not supplied, returns the default_indices.
"""
if indices is None:
indices = self.default_indices
if isinstance(indices, six.string_types):
indices = [indices]
return indices | [
"def",
"_validate_indices",
"(",
"self",
",",
"indices",
"=",
"None",
")",
":",
"if",
"indices",
"is",
"None",
":",
"indices",
"=",
"self",
".",
"default_indices",
"if",
"isinstance",
"(",
"indices",
",",
"six",
".",
"string_types",
")",
":",
"indices",
... | Return a valid list of indices.
`indices` may be a string or a list of strings.
If `indices` is not supplied, returns the default_indices. | [
"Return",
"a",
"valid",
"list",
"of",
"indices",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/es.py#L503-L513 | train | 29,305 |
aparo/pyes | pyes/es.py | ES.validate_types | def validate_types(self, types=None):
"""Return a valid list of types.
`types` may be a string or a list of strings.
If `types` is not supplied, returns the default_types.
"""
types = types or self.default_types
if types is None:
types = []
if isinstance(types, six.string_types):
types = [types]
return types | python | def validate_types(self, types=None):
"""Return a valid list of types.
`types` may be a string or a list of strings.
If `types` is not supplied, returns the default_types.
"""
types = types or self.default_types
if types is None:
types = []
if isinstance(types, six.string_types):
types = [types]
return types | [
"def",
"validate_types",
"(",
"self",
",",
"types",
"=",
"None",
")",
":",
"types",
"=",
"types",
"or",
"self",
".",
"default_types",
"if",
"types",
"is",
"None",
":",
"types",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"types",
",",
"six",
".",
"string... | Return a valid list of types.
`types` may be a string or a list of strings.
If `types` is not supplied, returns the default_types. | [
"Return",
"a",
"valid",
"list",
"of",
"types",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/es.py#L515-L527 | train | 29,306 |
aparo/pyes | pyes/es.py | ES.create_bulker | def create_bulker(self):
"""
Create a bulker object and return it to allow to manage custom bulk policies
"""
return self.bulker_class(self, bulk_size=self.bulk_size,
raise_on_bulk_item_failure=self.raise_on_bulk_item_failure) | python | def create_bulker(self):
"""
Create a bulker object and return it to allow to manage custom bulk policies
"""
return self.bulker_class(self, bulk_size=self.bulk_size,
raise_on_bulk_item_failure=self.raise_on_bulk_item_failure) | [
"def",
"create_bulker",
"(",
"self",
")",
":",
"return",
"self",
".",
"bulker_class",
"(",
"self",
",",
"bulk_size",
"=",
"self",
".",
"bulk_size",
",",
"raise_on_bulk_item_failure",
"=",
"self",
".",
"raise_on_bulk_item_failure",
")"
] | Create a bulker object and return it to allow to manage custom bulk policies | [
"Create",
"a",
"bulker",
"object",
"and",
"return",
"it",
"to",
"allow",
"to",
"manage",
"custom",
"bulk",
"policies"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/es.py#L562-L567 | train | 29,307 |
aparo/pyes | pyes/es.py | ES.ensure_index | def ensure_index(self, index, mappings=None, settings=None, clear=False):
"""
Ensure if an index with mapping exists
"""
mappings = mappings or []
if isinstance(mappings, dict):
mappings = [mappings]
exists = self.indices.exists_index(index)
if exists and not mappings and not clear:
return
if exists and clear:
self.indices.delete_index(index)
exists = False
if exists:
if not mappings:
self.indices.delete_index(index)
self.indices.refresh()
self.indices.create_index(index, settings)
return
if clear:
for maps in mappings:
for key in list(maps.keys()):
self.indices.delete_mapping(index, doc_type=key)
self.indices.refresh()
if isinstance(mappings, SettingsBuilder):
for name, data in list(mappings.mappings.items()):
self.indices.put_mapping(doc_type=name, mapping=data, indices=index)
else:
from pyes.mappings import DocumentObjectField, ObjectField
for maps in mappings:
if isinstance(maps, tuple):
name, mapping = maps
self.indices.put_mapping(doc_type=name, mapping=mapping, indices=index)
elif isinstance(maps, dict):
for name, data in list(maps.items()):
self.indices.put_mapping(doc_type=name, mapping=maps, indices=index)
elif isinstance(maps, (DocumentObjectField, ObjectField)):
self.put_mapping(doc_type=maps.name, mapping=maps.as_dict(), indices=index)
return
if settings:
if isinstance(settings, dict):
settings = SettingsBuilder(settings, mappings)
else:
if isinstance(mappings, SettingsBuilder):
settings = mappings
else:
settings = SettingsBuilder(mappings=mappings)
if not exists:
self.indices.create_index(index, settings)
self.indices.refresh(index, timesleep=1) | python | def ensure_index(self, index, mappings=None, settings=None, clear=False):
"""
Ensure if an index with mapping exists
"""
mappings = mappings or []
if isinstance(mappings, dict):
mappings = [mappings]
exists = self.indices.exists_index(index)
if exists and not mappings and not clear:
return
if exists and clear:
self.indices.delete_index(index)
exists = False
if exists:
if not mappings:
self.indices.delete_index(index)
self.indices.refresh()
self.indices.create_index(index, settings)
return
if clear:
for maps in mappings:
for key in list(maps.keys()):
self.indices.delete_mapping(index, doc_type=key)
self.indices.refresh()
if isinstance(mappings, SettingsBuilder):
for name, data in list(mappings.mappings.items()):
self.indices.put_mapping(doc_type=name, mapping=data, indices=index)
else:
from pyes.mappings import DocumentObjectField, ObjectField
for maps in mappings:
if isinstance(maps, tuple):
name, mapping = maps
self.indices.put_mapping(doc_type=name, mapping=mapping, indices=index)
elif isinstance(maps, dict):
for name, data in list(maps.items()):
self.indices.put_mapping(doc_type=name, mapping=maps, indices=index)
elif isinstance(maps, (DocumentObjectField, ObjectField)):
self.put_mapping(doc_type=maps.name, mapping=maps.as_dict(), indices=index)
return
if settings:
if isinstance(settings, dict):
settings = SettingsBuilder(settings, mappings)
else:
if isinstance(mappings, SettingsBuilder):
settings = mappings
else:
settings = SettingsBuilder(mappings=mappings)
if not exists:
self.indices.create_index(index, settings)
self.indices.refresh(index, timesleep=1) | [
"def",
"ensure_index",
"(",
"self",
",",
"index",
",",
"mappings",
"=",
"None",
",",
"settings",
"=",
"None",
",",
"clear",
"=",
"False",
")",
":",
"mappings",
"=",
"mappings",
"or",
"[",
"]",
"if",
"isinstance",
"(",
"mappings",
",",
"dict",
")",
":... | Ensure if an index with mapping exists | [
"Ensure",
"if",
"an",
"index",
"with",
"mapping",
"exists"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/es.py#L569-L624 | train | 29,308 |
aparo/pyes | pyes/es.py | ES.collect_info | def collect_info(self):
"""
Collect info about the connection and fill the info dictionary.
"""
try:
info = {}
res = self._send_request('GET', "/")
info['server'] = {}
info['server']['name'] = res['name']
info['server']['version'] = res['version']
info['allinfo'] = res
info['status'] = self.cluster.status()
info['aliases'] = self.indices.aliases()
self.info = info
return True
except:
self.info = {}
return False | python | def collect_info(self):
"""
Collect info about the connection and fill the info dictionary.
"""
try:
info = {}
res = self._send_request('GET', "/")
info['server'] = {}
info['server']['name'] = res['name']
info['server']['version'] = res['version']
info['allinfo'] = res
info['status'] = self.cluster.status()
info['aliases'] = self.indices.aliases()
self.info = info
return True
except:
self.info = {}
return False | [
"def",
"collect_info",
"(",
"self",
")",
":",
"try",
":",
"info",
"=",
"{",
"}",
"res",
"=",
"self",
".",
"_send_request",
"(",
"'GET'",
",",
"\"/\"",
")",
"info",
"[",
"'server'",
"]",
"=",
"{",
"}",
"info",
"[",
"'server'",
"]",
"[",
"'name'",
... | Collect info about the connection and fill the info dictionary. | [
"Collect",
"info",
"about",
"the",
"connection",
"and",
"fill",
"the",
"info",
"dictionary",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/es.py#L685-L702 | train | 29,309 |
aparo/pyes | pyes/es.py | ES.index_raw_bulk | def index_raw_bulk(self, header, document):
"""
Function helper for fast inserting
:param header: a string with the bulk header must be ended with a newline
:param document: a json document string must be ended with a newline
"""
self.bulker.add("%s%s" % (header, document))
return self.flush_bulk() | python | def index_raw_bulk(self, header, document):
"""
Function helper for fast inserting
:param header: a string with the bulk header must be ended with a newline
:param document: a json document string must be ended with a newline
"""
self.bulker.add("%s%s" % (header, document))
return self.flush_bulk() | [
"def",
"index_raw_bulk",
"(",
"self",
",",
"header",
",",
"document",
")",
":",
"self",
".",
"bulker",
".",
"add",
"(",
"\"%s%s\"",
"%",
"(",
"header",
",",
"document",
")",
")",
"return",
"self",
".",
"flush_bulk",
"(",
")"
] | Function helper for fast inserting
:param header: a string with the bulk header must be ended with a newline
:param document: a json document string must be ended with a newline | [
"Function",
"helper",
"for",
"fast",
"inserting"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/es.py#L704-L712 | train | 29,310 |
aparo/pyes | pyes/es.py | ES.index | def index(self, doc, index, doc_type, id=None, parent=None, force_insert=False,
op_type=None, bulk=False, version=None, querystring_args=None, ttl=None):
"""
Index a typed JSON document into a specific index and make it searchable.
"""
if querystring_args is None:
querystring_args = {}
if bulk:
if op_type is None:
op_type = "index"
if force_insert:
op_type = "create"
cmd = {op_type: {"_index": index, "_type": doc_type}}
if parent:
cmd[op_type]['_parent'] = parent
if version:
cmd[op_type]['_version'] = version
if 'routing' in querystring_args:
cmd[op_type]['_routing'] = querystring_args['routing']
if 'percolate' in querystring_args:
cmd[op_type]['percolate'] = querystring_args['percolate']
if id is not None: #None to support 0 as id
cmd[op_type]['_id'] = id
if ttl is not None:
cmd[op_type]['_ttl'] = ttl
if isinstance(doc, dict):
doc = json.dumps(doc, cls=self.encoder)
command = "%s\n%s" % (json.dumps(cmd, cls=self.encoder), doc)
self.bulker.add(command)
return self.flush_bulk()
if force_insert:
querystring_args['op_type'] = 'create'
if op_type:
querystring_args['op_type'] = op_type
if parent:
if not isinstance(parent, str):
parent = str(parent)
querystring_args['parent'] = parent
if version:
if not isinstance(version, str):
version = str(version)
querystring_args['version'] = version
if ttl is not None:
if not isinstance(ttl, str):
ttl = str(ttl)
querystring_args['ttl'] = ttl
if id is None:
request_method = 'POST'
else:
request_method = 'PUT'
path = make_path(index, doc_type, id)
return self._send_request(request_method, path, doc, querystring_args) | python | def index(self, doc, index, doc_type, id=None, parent=None, force_insert=False,
op_type=None, bulk=False, version=None, querystring_args=None, ttl=None):
"""
Index a typed JSON document into a specific index and make it searchable.
"""
if querystring_args is None:
querystring_args = {}
if bulk:
if op_type is None:
op_type = "index"
if force_insert:
op_type = "create"
cmd = {op_type: {"_index": index, "_type": doc_type}}
if parent:
cmd[op_type]['_parent'] = parent
if version:
cmd[op_type]['_version'] = version
if 'routing' in querystring_args:
cmd[op_type]['_routing'] = querystring_args['routing']
if 'percolate' in querystring_args:
cmd[op_type]['percolate'] = querystring_args['percolate']
if id is not None: #None to support 0 as id
cmd[op_type]['_id'] = id
if ttl is not None:
cmd[op_type]['_ttl'] = ttl
if isinstance(doc, dict):
doc = json.dumps(doc, cls=self.encoder)
command = "%s\n%s" % (json.dumps(cmd, cls=self.encoder), doc)
self.bulker.add(command)
return self.flush_bulk()
if force_insert:
querystring_args['op_type'] = 'create'
if op_type:
querystring_args['op_type'] = op_type
if parent:
if not isinstance(parent, str):
parent = str(parent)
querystring_args['parent'] = parent
if version:
if not isinstance(version, str):
version = str(version)
querystring_args['version'] = version
if ttl is not None:
if not isinstance(ttl, str):
ttl = str(ttl)
querystring_args['ttl'] = ttl
if id is None:
request_method = 'POST'
else:
request_method = 'PUT'
path = make_path(index, doc_type, id)
return self._send_request(request_method, path, doc, querystring_args) | [
"def",
"index",
"(",
"self",
",",
"doc",
",",
"index",
",",
"doc_type",
",",
"id",
"=",
"None",
",",
"parent",
"=",
"None",
",",
"force_insert",
"=",
"False",
",",
"op_type",
"=",
"None",
",",
"bulk",
"=",
"False",
",",
"version",
"=",
"None",
",",... | Index a typed JSON document into a specific index and make it searchable. | [
"Index",
"a",
"typed",
"JSON",
"document",
"into",
"a",
"specific",
"index",
"and",
"make",
"it",
"searchable",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/es.py#L714-L773 | train | 29,311 |
aparo/pyes | pyes/es.py | ES.put_file | def put_file(self, filename, index, doc_type, id=None, name=None):
"""
Store a file in a index
"""
if id is None:
request_method = 'POST'
else:
request_method = 'PUT'
path = make_path(index, doc_type, id)
doc = file_to_attachment(filename)
if name:
doc["_name"] = name
return self._send_request(request_method, path, doc) | python | def put_file(self, filename, index, doc_type, id=None, name=None):
"""
Store a file in a index
"""
if id is None:
request_method = 'POST'
else:
request_method = 'PUT'
path = make_path(index, doc_type, id)
doc = file_to_attachment(filename)
if name:
doc["_name"] = name
return self._send_request(request_method, path, doc) | [
"def",
"put_file",
"(",
"self",
",",
"filename",
",",
"index",
",",
"doc_type",
",",
"id",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"if",
"id",
"is",
"None",
":",
"request_method",
"=",
"'POST'",
"else",
":",
"request_method",
"=",
"'PUT'",
"... | Store a file in a index | [
"Store",
"a",
"file",
"in",
"a",
"index"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/es.py#L789-L801 | train | 29,312 |
aparo/pyes | pyes/es.py | ES.get_file | def get_file(self, index, doc_type, id=None):
"""
Return the filename and memory data stream
"""
data = self.get(index, doc_type, id)
return data['_name'], base64.standard_b64decode(data['content']) | python | def get_file(self, index, doc_type, id=None):
"""
Return the filename and memory data stream
"""
data = self.get(index, doc_type, id)
return data['_name'], base64.standard_b64decode(data['content']) | [
"def",
"get_file",
"(",
"self",
",",
"index",
",",
"doc_type",
",",
"id",
"=",
"None",
")",
":",
"data",
"=",
"self",
".",
"get",
"(",
"index",
",",
"doc_type",
",",
"id",
")",
"return",
"data",
"[",
"'_name'",
"]",
",",
"base64",
".",
"standard_b6... | Return the filename and memory data stream | [
"Return",
"the",
"filename",
"and",
"memory",
"data",
"stream"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/es.py#L803-L808 | train | 29,313 |
aparo/pyes | pyes/es.py | ES.update_by_function | def update_by_function(self, extra_doc, index, doc_type, id, querystring_args=None,
update_func=None, attempts=2):
"""
Update an already indexed typed JSON document.
The update happens client-side, i.e. the current document is retrieved,
updated locally and finally pushed to the server. This may repeat up to
``attempts`` times in case of version conflicts.
:param update_func: A callable ``update_func(current_doc, extra_doc)``
that computes and returns the updated doc. Alternatively it may
update ``current_doc`` in place and return None. The default
``update_func`` is ``dict.update``.
:param attempts: How many times to retry in case of version conflict.
"""
if querystring_args is None:
querystring_args = {}
if update_func is None:
update_func = dict.update
for attempt in range(attempts - 1, -1, -1):
current_doc = self.get(index, doc_type, id, **querystring_args)
new_doc = update_func(current_doc, extra_doc)
if new_doc is None:
new_doc = current_doc
try:
return self.index(new_doc, index, doc_type, id,
version=current_doc._meta.version, querystring_args=querystring_args)
except VersionConflictEngineException:
if attempt <= 0:
raise
self.refresh(index) | python | def update_by_function(self, extra_doc, index, doc_type, id, querystring_args=None,
update_func=None, attempts=2):
"""
Update an already indexed typed JSON document.
The update happens client-side, i.e. the current document is retrieved,
updated locally and finally pushed to the server. This may repeat up to
``attempts`` times in case of version conflicts.
:param update_func: A callable ``update_func(current_doc, extra_doc)``
that computes and returns the updated doc. Alternatively it may
update ``current_doc`` in place and return None. The default
``update_func`` is ``dict.update``.
:param attempts: How many times to retry in case of version conflict.
"""
if querystring_args is None:
querystring_args = {}
if update_func is None:
update_func = dict.update
for attempt in range(attempts - 1, -1, -1):
current_doc = self.get(index, doc_type, id, **querystring_args)
new_doc = update_func(current_doc, extra_doc)
if new_doc is None:
new_doc = current_doc
try:
return self.index(new_doc, index, doc_type, id,
version=current_doc._meta.version, querystring_args=querystring_args)
except VersionConflictEngineException:
if attempt <= 0:
raise
self.refresh(index) | [
"def",
"update_by_function",
"(",
"self",
",",
"extra_doc",
",",
"index",
",",
"doc_type",
",",
"id",
",",
"querystring_args",
"=",
"None",
",",
"update_func",
"=",
"None",
",",
"attempts",
"=",
"2",
")",
":",
"if",
"querystring_args",
"is",
"None",
":",
... | Update an already indexed typed JSON document.
The update happens client-side, i.e. the current document is retrieved,
updated locally and finally pushed to the server. This may repeat up to
``attempts`` times in case of version conflicts.
:param update_func: A callable ``update_func(current_doc, extra_doc)``
that computes and returns the updated doc. Alternatively it may
update ``current_doc`` in place and return None. The default
``update_func`` is ``dict.update``.
:param attempts: How many times to retry in case of version conflict. | [
"Update",
"an",
"already",
"indexed",
"typed",
"JSON",
"document",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/es.py#L851-L884 | train | 29,314 |
aparo/pyes | pyes/es.py | ES.partial_update | def partial_update(self, index, doc_type, id, doc=None, script=None, params=None,
upsert=None, querystring_args=None):
"""
Partially update a document with a script
"""
if querystring_args is None:
querystring_args = {}
if doc is None and script is None:
raise InvalidQuery("script or doc can not both be None")
if doc is None:
cmd = {"script": script}
if params:
cmd["params"] = params
if upsert:
cmd["upsert"] = upsert
else:
cmd = {"doc": doc }
path = make_path(index, doc_type, id, "_update")
return self._send_request('POST', path, cmd, querystring_args) | python | def partial_update(self, index, doc_type, id, doc=None, script=None, params=None,
upsert=None, querystring_args=None):
"""
Partially update a document with a script
"""
if querystring_args is None:
querystring_args = {}
if doc is None and script is None:
raise InvalidQuery("script or doc can not both be None")
if doc is None:
cmd = {"script": script}
if params:
cmd["params"] = params
if upsert:
cmd["upsert"] = upsert
else:
cmd = {"doc": doc }
path = make_path(index, doc_type, id, "_update")
return self._send_request('POST', path, cmd, querystring_args) | [
"def",
"partial_update",
"(",
"self",
",",
"index",
",",
"doc_type",
",",
"id",
",",
"doc",
"=",
"None",
",",
"script",
"=",
"None",
",",
"params",
"=",
"None",
",",
"upsert",
"=",
"None",
",",
"querystring_args",
"=",
"None",
")",
":",
"if",
"querys... | Partially update a document with a script | [
"Partially",
"update",
"a",
"document",
"with",
"a",
"script"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/es.py#L886-L907 | train | 29,315 |
aparo/pyes | pyes/es.py | ES.delete | def delete(self, index, doc_type, id, bulk=False, **query_params):
"""
Delete a typed JSON document from a specific index based on its id.
If bulk is True, the delete operation is put in bulk mode.
"""
if bulk:
cmd = {"delete": {"_index": index, "_type": doc_type,
"_id": id}}
self.bulker.add(json.dumps(cmd, cls=self.encoder))
return self.flush_bulk()
path = make_path(index, doc_type, id)
return self._send_request('DELETE', path, params=query_params) | python | def delete(self, index, doc_type, id, bulk=False, **query_params):
"""
Delete a typed JSON document from a specific index based on its id.
If bulk is True, the delete operation is put in bulk mode.
"""
if bulk:
cmd = {"delete": {"_index": index, "_type": doc_type,
"_id": id}}
self.bulker.add(json.dumps(cmd, cls=self.encoder))
return self.flush_bulk()
path = make_path(index, doc_type, id)
return self._send_request('DELETE', path, params=query_params) | [
"def",
"delete",
"(",
"self",
",",
"index",
",",
"doc_type",
",",
"id",
",",
"bulk",
"=",
"False",
",",
"*",
"*",
"query_params",
")",
":",
"if",
"bulk",
":",
"cmd",
"=",
"{",
"\"delete\"",
":",
"{",
"\"_index\"",
":",
"index",
",",
"\"_type\"",
":... | Delete a typed JSON document from a specific index based on its id.
If bulk is True, the delete operation is put in bulk mode. | [
"Delete",
"a",
"typed",
"JSON",
"document",
"from",
"a",
"specific",
"index",
"based",
"on",
"its",
"id",
".",
"If",
"bulk",
"is",
"True",
"the",
"delete",
"operation",
"is",
"put",
"in",
"bulk",
"mode",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/es.py#L909-L921 | train | 29,316 |
aparo/pyes | pyes/es.py | ES.delete_by_query | def delete_by_query(self, indices, doc_types, query, **query_params):
"""
Delete documents from one or more indices and one or more types based on a query.
"""
path = self._make_path(indices, doc_types, '_query')
body = {"query": query.serialize()}
return self._send_request('DELETE', path, body, query_params) | python | def delete_by_query(self, indices, doc_types, query, **query_params):
"""
Delete documents from one or more indices and one or more types based on a query.
"""
path = self._make_path(indices, doc_types, '_query')
body = {"query": query.serialize()}
return self._send_request('DELETE', path, body, query_params) | [
"def",
"delete_by_query",
"(",
"self",
",",
"indices",
",",
"doc_types",
",",
"query",
",",
"*",
"*",
"query_params",
")",
":",
"path",
"=",
"self",
".",
"_make_path",
"(",
"indices",
",",
"doc_types",
",",
"'_query'",
")",
"body",
"=",
"{",
"\"query\"",... | Delete documents from one or more indices and one or more types based on a query. | [
"Delete",
"documents",
"from",
"one",
"or",
"more",
"indices",
"and",
"one",
"or",
"more",
"types",
"based",
"on",
"a",
"query",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/es.py#L923-L929 | train | 29,317 |
aparo/pyes | pyes/es.py | ES.exists | def exists(self, index, doc_type, id, **query_params):
"""
Return if a document exists
"""
path = make_path(index, doc_type, id)
return self._send_request('HEAD', path, params=query_params) | python | def exists(self, index, doc_type, id, **query_params):
"""
Return if a document exists
"""
path = make_path(index, doc_type, id)
return self._send_request('HEAD', path, params=query_params) | [
"def",
"exists",
"(",
"self",
",",
"index",
",",
"doc_type",
",",
"id",
",",
"*",
"*",
"query_params",
")",
":",
"path",
"=",
"make_path",
"(",
"index",
",",
"doc_type",
",",
"id",
")",
"return",
"self",
".",
"_send_request",
"(",
"'HEAD'",
",",
"pat... | Return if a document exists | [
"Return",
"if",
"a",
"document",
"exists"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/es.py#L931-L936 | train | 29,318 |
aparo/pyes | pyes/es.py | ES.get | def get(self, index, doc_type, id, fields=None, model=None, **query_params):
"""
Get a typed JSON document from an index based on its id.
"""
path = make_path(index, doc_type, id)
if fields is not None:
query_params["fields"] = ",".join(fields)
model = model or self.model
return model(self, self._send_request('GET', path, params=query_params)) | python | def get(self, index, doc_type, id, fields=None, model=None, **query_params):
"""
Get a typed JSON document from an index based on its id.
"""
path = make_path(index, doc_type, id)
if fields is not None:
query_params["fields"] = ",".join(fields)
model = model or self.model
return model(self, self._send_request('GET', path, params=query_params)) | [
"def",
"get",
"(",
"self",
",",
"index",
",",
"doc_type",
",",
"id",
",",
"fields",
"=",
"None",
",",
"model",
"=",
"None",
",",
"*",
"*",
"query_params",
")",
":",
"path",
"=",
"make_path",
"(",
"index",
",",
"doc_type",
",",
"id",
")",
"if",
"f... | Get a typed JSON document from an index based on its id. | [
"Get",
"a",
"typed",
"JSON",
"document",
"from",
"an",
"index",
"based",
"on",
"its",
"id",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/es.py#L938-L946 | train | 29,319 |
aparo/pyes | pyes/es.py | ES.factory_object | def factory_object(self, index, doc_type, data=None, id=None):
"""
Create a stub object to be manipulated
"""
data = data or {}
obj = self.model()
obj._meta.index = index
obj._meta.type = doc_type
obj._meta.connection = self
if id:
obj._meta.id = id
if data:
obj.update(data)
return obj | python | def factory_object(self, index, doc_type, data=None, id=None):
"""
Create a stub object to be manipulated
"""
data = data or {}
obj = self.model()
obj._meta.index = index
obj._meta.type = doc_type
obj._meta.connection = self
if id:
obj._meta.id = id
if data:
obj.update(data)
return obj | [
"def",
"factory_object",
"(",
"self",
",",
"index",
",",
"doc_type",
",",
"data",
"=",
"None",
",",
"id",
"=",
"None",
")",
":",
"data",
"=",
"data",
"or",
"{",
"}",
"obj",
"=",
"self",
".",
"model",
"(",
")",
"obj",
".",
"_meta",
".",
"index",
... | Create a stub object to be manipulated | [
"Create",
"a",
"stub",
"object",
"to",
"be",
"manipulated"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/es.py#L948-L961 | train | 29,320 |
aparo/pyes | pyes/es.py | ES.mget | def mget(self, ids, index=None, doc_type=None, **query_params):
"""
Get multi JSON documents.
ids can be:
list of tuple: (index, type, id)
list of ids: index and doc_type are required
"""
if not ids:
return []
body = []
for value in ids:
if isinstance(value, tuple):
if len(value) == 3:
a, b, c = value
body.append({"_index": a,
"_type": b,
"_id": c})
elif len(value) == 4:
a, b, c, d = value
body.append({"_index": a,
"_type": b,
"_id": c,
"fields": d})
else:
if index is None:
raise InvalidQuery("index value is required for id")
if doc_type is None:
raise InvalidQuery("doc_type value is required for id")
body.append({"_index": index,
"_type": doc_type,
"_id": value})
results = self._send_request('GET', "/_mget", body={'docs': body},
params=query_params)
if 'docs' in results:
model = self.model
return [model(self, item) for item in results['docs']]
return [] | python | def mget(self, ids, index=None, doc_type=None, **query_params):
"""
Get multi JSON documents.
ids can be:
list of tuple: (index, type, id)
list of ids: index and doc_type are required
"""
if not ids:
return []
body = []
for value in ids:
if isinstance(value, tuple):
if len(value) == 3:
a, b, c = value
body.append({"_index": a,
"_type": b,
"_id": c})
elif len(value) == 4:
a, b, c, d = value
body.append({"_index": a,
"_type": b,
"_id": c,
"fields": d})
else:
if index is None:
raise InvalidQuery("index value is required for id")
if doc_type is None:
raise InvalidQuery("doc_type value is required for id")
body.append({"_index": index,
"_type": doc_type,
"_id": value})
results = self._send_request('GET', "/_mget", body={'docs': body},
params=query_params)
if 'docs' in results:
model = self.model
return [model(self, item) for item in results['docs']]
return [] | [
"def",
"mget",
"(",
"self",
",",
"ids",
",",
"index",
"=",
"None",
",",
"doc_type",
"=",
"None",
",",
"*",
"*",
"query_params",
")",
":",
"if",
"not",
"ids",
":",
"return",
"[",
"]",
"body",
"=",
"[",
"]",
"for",
"value",
"in",
"ids",
":",
"if"... | Get multi JSON documents.
ids can be:
list of tuple: (index, type, id)
list of ids: index and doc_type are required | [
"Get",
"multi",
"JSON",
"documents",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/es.py#L963-L1003 | train | 29,321 |
aparo/pyes | pyes/es.py | ES.search_raw | def search_raw(self, query, indices=None, doc_types=None, headers=None, **query_params):
"""Execute a search against one or more indices to get the search hits.
`query` must be a Search object, a Query object, or a custom
dictionary of search parameters using the query DSL to be passed
directly.
"""
from .query import Search, Query
if isinstance(query, Query):
query = query.search()
if isinstance(query, Search):
query = query.serialize()
body = self._encode_query(query)
path = self._make_path(indices, doc_types, "_search")
return self._send_request('GET', path, body, params=query_params, headers=headers) | python | def search_raw(self, query, indices=None, doc_types=None, headers=None, **query_params):
"""Execute a search against one or more indices to get the search hits.
`query` must be a Search object, a Query object, or a custom
dictionary of search parameters using the query DSL to be passed
directly.
"""
from .query import Search, Query
if isinstance(query, Query):
query = query.search()
if isinstance(query, Search):
query = query.serialize()
body = self._encode_query(query)
path = self._make_path(indices, doc_types, "_search")
return self._send_request('GET', path, body, params=query_params, headers=headers) | [
"def",
"search_raw",
"(",
"self",
",",
"query",
",",
"indices",
"=",
"None",
",",
"doc_types",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"*",
"*",
"query_params",
")",
":",
"from",
".",
"query",
"import",
"Search",
",",
"Query",
"if",
"isinstance"... | Execute a search against one or more indices to get the search hits.
`query` must be a Search object, a Query object, or a custom
dictionary of search parameters using the query DSL to be passed
directly. | [
"Execute",
"a",
"search",
"against",
"one",
"or",
"more",
"indices",
"to",
"get",
"the",
"search",
"hits",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/es.py#L1005-L1020 | train | 29,322 |
aparo/pyes | pyes/es.py | ES.search | def search(self, query, indices=None, doc_types=None, model=None, scan=False, headers=None, **query_params):
"""Execute a search against one or more indices to get the resultset.
`query` must be a Search object, a Query object, or a custom
dictionary of search parameters using the query DSL to be passed
directly.
"""
if isinstance(query, Search):
search = query
elif isinstance(query, (Query, dict)):
search = Search(query)
else:
raise InvalidQuery("search() must be supplied with a Search or Query object, or a dict")
if scan:
query_params.setdefault("search_type", "scan")
query_params.setdefault("scroll", "10m")
return ResultSet(self, search, indices=indices, doc_types=doc_types,
model=model, query_params=query_params, headers=headers) | python | def search(self, query, indices=None, doc_types=None, model=None, scan=False, headers=None, **query_params):
"""Execute a search against one or more indices to get the resultset.
`query` must be a Search object, a Query object, or a custom
dictionary of search parameters using the query DSL to be passed
directly.
"""
if isinstance(query, Search):
search = query
elif isinstance(query, (Query, dict)):
search = Search(query)
else:
raise InvalidQuery("search() must be supplied with a Search or Query object, or a dict")
if scan:
query_params.setdefault("search_type", "scan")
query_params.setdefault("scroll", "10m")
return ResultSet(self, search, indices=indices, doc_types=doc_types,
model=model, query_params=query_params, headers=headers) | [
"def",
"search",
"(",
"self",
",",
"query",
",",
"indices",
"=",
"None",
",",
"doc_types",
"=",
"None",
",",
"model",
"=",
"None",
",",
"scan",
"=",
"False",
",",
"headers",
"=",
"None",
",",
"*",
"*",
"query_params",
")",
":",
"if",
"isinstance",
... | Execute a search against one or more indices to get the resultset.
`query` must be a Search object, a Query object, or a custom
dictionary of search parameters using the query DSL to be passed
directly. | [
"Execute",
"a",
"search",
"against",
"one",
"or",
"more",
"indices",
"to",
"get",
"the",
"resultset",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/es.py#L1067-L1086 | train | 29,323 |
aparo/pyes | pyes/es.py | ES.suggest | def suggest(self, name, text, field, type='term', size=None, params=None,
**kwargs):
"""
Execute suggester of given type.
:param name: name for the suggester
:param text: text to search for
:param field: field to search
:param type: One of: completion, phrase, term
:param size: number of results
:param params: additional suggester params
:param kwargs:
:return:
"""
from .query import Suggest
suggest = Suggest()
suggest.add(text, name, field, type=type, size=size, params=params)
return self.suggest_from_object(suggest, **kwargs) | python | def suggest(self, name, text, field, type='term', size=None, params=None,
**kwargs):
"""
Execute suggester of given type.
:param name: name for the suggester
:param text: text to search for
:param field: field to search
:param type: One of: completion, phrase, term
:param size: number of results
:param params: additional suggester params
:param kwargs:
:return:
"""
from .query import Suggest
suggest = Suggest()
suggest.add(text, name, field, type=type, size=size, params=params)
return self.suggest_from_object(suggest, **kwargs) | [
"def",
"suggest",
"(",
"self",
",",
"name",
",",
"text",
",",
"field",
",",
"type",
"=",
"'term'",
",",
"size",
"=",
"None",
",",
"params",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
"query",
"import",
"Suggest",
"suggest",
"=",
... | Execute suggester of given type.
:param name: name for the suggester
:param text: text to search for
:param field: field to search
:param type: One of: completion, phrase, term
:param size: number of results
:param params: additional suggester params
:param kwargs:
:return: | [
"Execute",
"suggester",
"of",
"given",
"type",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/es.py#L1138-L1159 | train | 29,324 |
aparo/pyes | pyes/es.py | ES.count | def count(self, query=None, indices=None, doc_types=None, **query_params):
"""
Execute a query against one or more indices and get hits count.
"""
from .query import MatchAllQuery
if query is None:
query = MatchAllQuery()
body = {"query": query.serialize()}
path = self._make_path(indices, doc_types, "_count")
return self._send_request('GET', path, body, params=query_params) | python | def count(self, query=None, indices=None, doc_types=None, **query_params):
"""
Execute a query against one or more indices and get hits count.
"""
from .query import MatchAllQuery
if query is None:
query = MatchAllQuery()
body = {"query": query.serialize()}
path = self._make_path(indices, doc_types, "_count")
return self._send_request('GET', path, body, params=query_params) | [
"def",
"count",
"(",
"self",
",",
"query",
"=",
"None",
",",
"indices",
"=",
"None",
",",
"doc_types",
"=",
"None",
",",
"*",
"*",
"query_params",
")",
":",
"from",
".",
"query",
"import",
"MatchAllQuery",
"if",
"query",
"is",
"None",
":",
"query",
"... | Execute a query against one or more indices and get hits count. | [
"Execute",
"a",
"query",
"against",
"one",
"or",
"more",
"indices",
"and",
"get",
"hits",
"count",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/es.py#L1162-L1172 | train | 29,325 |
aparo/pyes | pyes/es.py | ES.create_river | def create_river(self, river, river_name=None):
"""
Create a river
"""
if isinstance(river, River):
body = river.serialize()
river_name = river.name
else:
body = river
return self._send_request('PUT', '/_river/%s/_meta' % river_name, body) | python | def create_river(self, river, river_name=None):
"""
Create a river
"""
if isinstance(river, River):
body = river.serialize()
river_name = river.name
else:
body = river
return self._send_request('PUT', '/_river/%s/_meta' % river_name, body) | [
"def",
"create_river",
"(",
"self",
",",
"river",
",",
"river_name",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"river",
",",
"River",
")",
":",
"body",
"=",
"river",
".",
"serialize",
"(",
")",
"river_name",
"=",
"river",
".",
"name",
"else",
"... | Create a river | [
"Create",
"a",
"river"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/es.py#L1175-L1184 | train | 29,326 |
aparo/pyes | pyes/es.py | ES.delete_river | def delete_river(self, river, river_name=None):
"""
Delete a river
"""
if isinstance(river, River):
river_name = river.name
return self._send_request('DELETE', '/_river/%s/' % river_name) | python | def delete_river(self, river, river_name=None):
"""
Delete a river
"""
if isinstance(river, River):
river_name = river.name
return self._send_request('DELETE', '/_river/%s/' % river_name) | [
"def",
"delete_river",
"(",
"self",
",",
"river",
",",
"river_name",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"river",
",",
"River",
")",
":",
"river_name",
"=",
"river",
".",
"name",
"return",
"self",
".",
"_send_request",
"(",
"'DELETE'",
",",
... | Delete a river | [
"Delete",
"a",
"river"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/es.py#L1186-L1192 | train | 29,327 |
aparo/pyes | pyes/es.py | ES.morelikethis | def morelikethis(self, index, doc_type, id, fields, **query_params):
"""
Execute a "more like this" search query against one or more fields and get back search hits.
"""
path = make_path(index, doc_type, id, '_mlt')
query_params['mlt_fields'] = ','.join(fields)
body = query_params["body"] if "body" in query_params else None
return self._send_request('GET', path, body=body, params=query_params) | python | def morelikethis(self, index, doc_type, id, fields, **query_params):
"""
Execute a "more like this" search query against one or more fields and get back search hits.
"""
path = make_path(index, doc_type, id, '_mlt')
query_params['mlt_fields'] = ','.join(fields)
body = query_params["body"] if "body" in query_params else None
return self._send_request('GET', path, body=body, params=query_params) | [
"def",
"morelikethis",
"(",
"self",
",",
"index",
",",
"doc_type",
",",
"id",
",",
"fields",
",",
"*",
"*",
"query_params",
")",
":",
"path",
"=",
"make_path",
"(",
"index",
",",
"doc_type",
",",
"id",
",",
"'_mlt'",
")",
"query_params",
"[",
"'mlt_fie... | Execute a "more like this" search query against one or more fields and get back search hits. | [
"Execute",
"a",
"more",
"like",
"this",
"search",
"query",
"against",
"one",
"or",
"more",
"fields",
"and",
"get",
"back",
"search",
"hits",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/es.py#L1214-L1221 | train | 29,328 |
aparo/pyes | pyes/es.py | ES.create_percolator | def create_percolator(self, index, name, query, **kwargs):
"""
Create a percolator document
Any kwargs will be added to the document as extra properties.
"""
if isinstance(query, Query):
query = {"query": query.serialize()}
if not isinstance(query, dict):
raise InvalidQuery("create_percolator() must be supplied with a Query object or dict")
if kwargs:
query.update(kwargs)
path = make_path(index, '.percolator', name)
body = json.dumps(query, cls=self.encoder)
return self._send_request('PUT', path, body) | python | def create_percolator(self, index, name, query, **kwargs):
"""
Create a percolator document
Any kwargs will be added to the document as extra properties.
"""
if isinstance(query, Query):
query = {"query": query.serialize()}
if not isinstance(query, dict):
raise InvalidQuery("create_percolator() must be supplied with a Query object or dict")
if kwargs:
query.update(kwargs)
path = make_path(index, '.percolator', name)
body = json.dumps(query, cls=self.encoder)
return self._send_request('PUT', path, body) | [
"def",
"create_percolator",
"(",
"self",
",",
"index",
",",
"name",
",",
"query",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"query",
",",
"Query",
")",
":",
"query",
"=",
"{",
"\"query\"",
":",
"query",
".",
"serialize",
"(",
")",
... | Create a percolator document
Any kwargs will be added to the document as extra properties. | [
"Create",
"a",
"percolator",
"document"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/es.py#L1223-L1238 | train | 29,329 |
aparo/pyes | pyes/es.py | ES.percolate | def percolate(self, index, doc_types, query):
"""
Match a query with a document
"""
if doc_types is None:
raise RuntimeError('percolate() must be supplied with at least one doc_type')
path = self._make_path(index, doc_types, '_percolate')
body = self._encode_query(query)
return self._send_request('GET', path, body) | python | def percolate(self, index, doc_types, query):
"""
Match a query with a document
"""
if doc_types is None:
raise RuntimeError('percolate() must be supplied with at least one doc_type')
path = self._make_path(index, doc_types, '_percolate')
body = self._encode_query(query)
return self._send_request('GET', path, body) | [
"def",
"percolate",
"(",
"self",
",",
"index",
",",
"doc_types",
",",
"query",
")",
":",
"if",
"doc_types",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"'percolate() must be supplied with at least one doc_type'",
")",
"path",
"=",
"self",
".",
"_make_path",
... | Match a query with a document | [
"Match",
"a",
"query",
"with",
"a",
"document"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/es.py#L1246-L1255 | train | 29,330 |
aparo/pyes | pyes/es.py | ResultSet.fix_facets | def fix_facets(self):
"""
This function convert date_histogram facets to datetime
"""
facets = self.facets
for key in list(facets.keys()):
_type = facets[key].get("_type", "unknown")
if _type == "date_histogram":
for entry in facets[key].get("entries", []):
for k, v in list(entry.items()):
if k in ["count", "max", "min", "total_count", "mean", "total"]:
continue
if not isinstance(entry[k], datetime):
entry[k] = datetime.utcfromtimestamp(v / 1e3) | python | def fix_facets(self):
"""
This function convert date_histogram facets to datetime
"""
facets = self.facets
for key in list(facets.keys()):
_type = facets[key].get("_type", "unknown")
if _type == "date_histogram":
for entry in facets[key].get("entries", []):
for k, v in list(entry.items()):
if k in ["count", "max", "min", "total_count", "mean", "total"]:
continue
if not isinstance(entry[k], datetime):
entry[k] = datetime.utcfromtimestamp(v / 1e3) | [
"def",
"fix_facets",
"(",
"self",
")",
":",
"facets",
"=",
"self",
".",
"facets",
"for",
"key",
"in",
"list",
"(",
"facets",
".",
"keys",
"(",
")",
")",
":",
"_type",
"=",
"facets",
"[",
"key",
"]",
".",
"get",
"(",
"\"_type\"",
",",
"\"unknown\"",... | This function convert date_histogram facets to datetime | [
"This",
"function",
"convert",
"date_histogram",
"facets",
"to",
"datetime"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/es.py#L1501-L1514 | train | 29,331 |
aparo/pyes | pyes/es.py | ResultSet.fix_aggs | def fix_aggs(self):
"""
This function convert date_histogram aggs to datetime
"""
aggs = self.aggs
for key in list(aggs.keys()):
_type = aggs[key].get("_type", "unknown")
if _type == "date_histogram":
for entry in aggs[key].get("entries", []):
for k, v in list(entry.items()):
if k in ["count", "max", "min", "total_count", "mean", "total"]:
continue
if not isinstance(entry[k], datetime):
entry[k] = datetime.utcfromtimestamp(v / 1e3) | python | def fix_aggs(self):
"""
This function convert date_histogram aggs to datetime
"""
aggs = self.aggs
for key in list(aggs.keys()):
_type = aggs[key].get("_type", "unknown")
if _type == "date_histogram":
for entry in aggs[key].get("entries", []):
for k, v in list(entry.items()):
if k in ["count", "max", "min", "total_count", "mean", "total"]:
continue
if not isinstance(entry[k], datetime):
entry[k] = datetime.utcfromtimestamp(v / 1e3) | [
"def",
"fix_aggs",
"(",
"self",
")",
":",
"aggs",
"=",
"self",
".",
"aggs",
"for",
"key",
"in",
"list",
"(",
"aggs",
".",
"keys",
"(",
")",
")",
":",
"_type",
"=",
"aggs",
"[",
"key",
"]",
".",
"get",
"(",
"\"_type\"",
",",
"\"unknown\"",
")",
... | This function convert date_histogram aggs to datetime | [
"This",
"function",
"convert",
"date_histogram",
"aggs",
"to",
"datetime"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/es.py#L1516-L1529 | train | 29,332 |
aparo/pyes | pyes/es.py | ResultSet.fix_keys | def fix_keys(self):
"""
Remove the _ from the keys of the results
"""
if not self.valid:
return
for hit in self._results['hits']['hits']:
for key, item in list(hit.items()):
if key.startswith("_"):
hit[key[1:]] = item
del hit[key] | python | def fix_keys(self):
"""
Remove the _ from the keys of the results
"""
if not self.valid:
return
for hit in self._results['hits']['hits']:
for key, item in list(hit.items()):
if key.startswith("_"):
hit[key[1:]] = item
del hit[key] | [
"def",
"fix_keys",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"valid",
":",
"return",
"for",
"hit",
"in",
"self",
".",
"_results",
"[",
"'hits'",
"]",
"[",
"'hits'",
"]",
":",
"for",
"key",
",",
"item",
"in",
"list",
"(",
"hit",
".",
"items... | Remove the _ from the keys of the results | [
"Remove",
"the",
"_",
"from",
"the",
"keys",
"of",
"the",
"results"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/es.py#L1537-L1548 | train | 29,333 |
aparo/pyes | pyes/es.py | ResultSet.clean_highlight | def clean_highlight(self):
"""
Remove the empty highlight
"""
if not self.valid:
return
for hit in self._results['hits']['hits']:
if 'highlight' in hit:
hl = hit['highlight']
for key, item in list(hl.items()):
if not item:
del hl[key] | python | def clean_highlight(self):
"""
Remove the empty highlight
"""
if not self.valid:
return
for hit in self._results['hits']['hits']:
if 'highlight' in hit:
hl = hit['highlight']
for key, item in list(hl.items()):
if not item:
del hl[key] | [
"def",
"clean_highlight",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"valid",
":",
"return",
"for",
"hit",
"in",
"self",
".",
"_results",
"[",
"'hits'",
"]",
"[",
"'hits'",
"]",
":",
"if",
"'highlight'",
"in",
"hit",
":",
"hl",
"=",
"hit",
"[... | Remove the empty highlight | [
"Remove",
"the",
"empty",
"highlight"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/es.py#L1550-L1562 | train | 29,334 |
aparo/pyes | pyes/highlight.py | HighLighter.add_field | def add_field(self, name, fragment_size=150, number_of_fragments=3, fragment_offset=None, order="score", type=None):
"""
Add a field to Highlinghter
"""
data = {}
if fragment_size:
data['fragment_size'] = fragment_size
if number_of_fragments is not None:
data['number_of_fragments'] = number_of_fragments
if fragment_offset is not None:
data['fragment_offset'] = fragment_offset
if type is not None:
data['type'] = type
data['order'] = order
self.fields[name] = data | python | def add_field(self, name, fragment_size=150, number_of_fragments=3, fragment_offset=None, order="score", type=None):
"""
Add a field to Highlinghter
"""
data = {}
if fragment_size:
data['fragment_size'] = fragment_size
if number_of_fragments is not None:
data['number_of_fragments'] = number_of_fragments
if fragment_offset is not None:
data['fragment_offset'] = fragment_offset
if type is not None:
data['type'] = type
data['order'] = order
self.fields[name] = data | [
"def",
"add_field",
"(",
"self",
",",
"name",
",",
"fragment_size",
"=",
"150",
",",
"number_of_fragments",
"=",
"3",
",",
"fragment_offset",
"=",
"None",
",",
"order",
"=",
"\"score\"",
",",
"type",
"=",
"None",
")",
":",
"data",
"=",
"{",
"}",
"if",
... | Add a field to Highlinghter | [
"Add",
"a",
"field",
"to",
"Highlinghter"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/highlight.py#L34-L48 | train | 29,335 |
aparo/pyes | pyes/queryset.py | QuerySet.iterator | def iterator(self):
"""
An iterator over the results from applying this QuerySet to the
database.
"""
if not self._result_cache:
len(self)
for r in self._result_cache:
yield r | python | def iterator(self):
"""
An iterator over the results from applying this QuerySet to the
database.
"""
if not self._result_cache:
len(self)
for r in self._result_cache:
yield r | [
"def",
"iterator",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_result_cache",
":",
"len",
"(",
"self",
")",
"for",
"r",
"in",
"self",
".",
"_result_cache",
":",
"yield",
"r"
] | An iterator over the results from applying this QuerySet to the
database. | [
"An",
"iterator",
"over",
"the",
"results",
"from",
"applying",
"this",
"QuerySet",
"to",
"the",
"database",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/queryset.py#L278-L286 | train | 29,336 |
aparo/pyes | pyes/queryset.py | QuerySet.in_bulk | def in_bulk(self, id_list):
"""
Returns a dictionary mapping each of the given IDs to the object with
that ID.
"""
if not id_list:
return {}
qs = self._clone()
qs.add_filter(('pk__in', id_list))
qs._clear_ordering(force_empty=True)
return dict([(obj._get_pk_val(), obj) for obj in qs]) | python | def in_bulk(self, id_list):
"""
Returns a dictionary mapping each of the given IDs to the object with
that ID.
"""
if not id_list:
return {}
qs = self._clone()
qs.add_filter(('pk__in', id_list))
qs._clear_ordering(force_empty=True)
return dict([(obj._get_pk_val(), obj) for obj in qs]) | [
"def",
"in_bulk",
"(",
"self",
",",
"id_list",
")",
":",
"if",
"not",
"id_list",
":",
"return",
"{",
"}",
"qs",
"=",
"self",
".",
"_clone",
"(",
")",
"qs",
".",
"add_filter",
"(",
"(",
"'pk__in'",
",",
"id_list",
")",
")",
"qs",
".",
"_clear_orderi... | Returns a dictionary mapping each of the given IDs to the object with
that ID. | [
"Returns",
"a",
"dictionary",
"mapping",
"each",
"of",
"the",
"given",
"IDs",
"to",
"the",
"object",
"with",
"that",
"ID",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/queryset.py#L430-L440 | train | 29,337 |
aparo/pyes | pyes/queryset.py | QuerySet.complex_filter | def complex_filter(self, filter_obj):
"""
Returns a new QuerySet instance with filter_obj added to the filters.
filter_obj can be a Q object (or anything with an add_to_query()
method) or a dictionary of keyword lookup arguments.
This exists to support framework features such as 'limit_choices_to',
and usually it will be more natural to use other methods.
"""
if isinstance(filter_obj, Filter):
clone = self._clone()
clone._filters.add(filter_obj)
return clone
return self._filter_or_exclude(None, **filter_obj) | python | def complex_filter(self, filter_obj):
"""
Returns a new QuerySet instance with filter_obj added to the filters.
filter_obj can be a Q object (or anything with an add_to_query()
method) or a dictionary of keyword lookup arguments.
This exists to support framework features such as 'limit_choices_to',
and usually it will be more natural to use other methods.
"""
if isinstance(filter_obj, Filter):
clone = self._clone()
clone._filters.add(filter_obj)
return clone
return self._filter_or_exclude(None, **filter_obj) | [
"def",
"complex_filter",
"(",
"self",
",",
"filter_obj",
")",
":",
"if",
"isinstance",
"(",
"filter_obj",
",",
"Filter",
")",
":",
"clone",
"=",
"self",
".",
"_clone",
"(",
")",
"clone",
".",
"_filters",
".",
"add",
"(",
"filter_obj",
")",
"return",
"c... | Returns a new QuerySet instance with filter_obj added to the filters.
filter_obj can be a Q object (or anything with an add_to_query()
method) or a dictionary of keyword lookup arguments.
This exists to support framework features such as 'limit_choices_to',
and usually it will be more natural to use other methods. | [
"Returns",
"a",
"new",
"QuerySet",
"instance",
"with",
"filter_obj",
"added",
"to",
"the",
"filters",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/queryset.py#L632-L646 | train | 29,338 |
aparo/pyes | pyes/queryset.py | QuerySet.reverse | def reverse(self):
"""
Reverses the ordering of the QuerySet.
"""
clone = self._clone()
assert self._ordering, "You need to set an ordering for reverse"
ordering = []
for order in self._ordering:
for k,v in order.items():
if v=="asc":
ordering.append({k: "desc"})
else:
ordering.append({k: "asc"})
clone._ordering=ordering
return clone | python | def reverse(self):
"""
Reverses the ordering of the QuerySet.
"""
clone = self._clone()
assert self._ordering, "You need to set an ordering for reverse"
ordering = []
for order in self._ordering:
for k,v in order.items():
if v=="asc":
ordering.append({k: "desc"})
else:
ordering.append({k: "asc"})
clone._ordering=ordering
return clone | [
"def",
"reverse",
"(",
"self",
")",
":",
"clone",
"=",
"self",
".",
"_clone",
"(",
")",
"assert",
"self",
".",
"_ordering",
",",
"\"You need to set an ordering for reverse\"",
"ordering",
"=",
"[",
"]",
"for",
"order",
"in",
"self",
".",
"_ordering",
":",
... | Reverses the ordering of the QuerySet. | [
"Reverses",
"the",
"ordering",
"of",
"the",
"QuerySet",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/queryset.py#L706-L720 | train | 29,339 |
aparo/pyes | pyes/queryset.py | QuerySet.only | def only(self, *fields):
"""
Essentially, the opposite of defer. Only the fields passed into this
method and that are not already specified as deferred are loaded
immediately when the queryset is evaluated.
"""
clone = self._clone()
clone._fields=fields
return clone | python | def only(self, *fields):
"""
Essentially, the opposite of defer. Only the fields passed into this
method and that are not already specified as deferred are loaded
immediately when the queryset is evaluated.
"""
clone = self._clone()
clone._fields=fields
return clone | [
"def",
"only",
"(",
"self",
",",
"*",
"fields",
")",
":",
"clone",
"=",
"self",
".",
"_clone",
"(",
")",
"clone",
".",
"_fields",
"=",
"fields",
"return",
"clone"
] | Essentially, the opposite of defer. Only the fields passed into this
method and that are not already specified as deferred are loaded
immediately when the queryset is evaluated. | [
"Essentially",
"the",
"opposite",
"of",
"defer",
".",
"Only",
"the",
"fields",
"passed",
"into",
"this",
"method",
"and",
"that",
"are",
"not",
"already",
"specified",
"as",
"deferred",
"are",
"loaded",
"immediately",
"when",
"the",
"queryset",
"is",
"evaluate... | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/queryset.py#L738-L746 | train | 29,340 |
aparo/pyes | pyes/queryset.py | QuerySet.using | def using(self, alias):
"""
Selects which database this QuerySet should excecute its query against.
"""
clone = self._clone()
clone._index = alias
return clone | python | def using(self, alias):
"""
Selects which database this QuerySet should excecute its query against.
"""
clone = self._clone()
clone._index = alias
return clone | [
"def",
"using",
"(",
"self",
",",
"alias",
")",
":",
"clone",
"=",
"self",
".",
"_clone",
"(",
")",
"clone",
".",
"_index",
"=",
"alias",
"return",
"clone"
] | Selects which database this QuerySet should excecute its query against. | [
"Selects",
"which",
"database",
"this",
"QuerySet",
"should",
"excecute",
"its",
"query",
"against",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/queryset.py#L748-L754 | train | 29,341 |
aparo/pyes | pyes/queryset.py | QuerySet.from_qs | def from_qs(cls, qs, **kwargs):
"""
Creates a new queryset using class `cls` using `qs'` data.
:param qs: The query set to clone
:keyword kwargs: The kwargs to pass to _clone method
"""
assert issubclass(cls, QuerySet), "%s is not a QuerySet subclass" % cls
assert isinstance(qs, QuerySet), "qs has to be an instance of queryset"
return qs._clone(klass=cls, **kwargs) | python | def from_qs(cls, qs, **kwargs):
"""
Creates a new queryset using class `cls` using `qs'` data.
:param qs: The query set to clone
:keyword kwargs: The kwargs to pass to _clone method
"""
assert issubclass(cls, QuerySet), "%s is not a QuerySet subclass" % cls
assert isinstance(qs, QuerySet), "qs has to be an instance of queryset"
return qs._clone(klass=cls, **kwargs) | [
"def",
"from_qs",
"(",
"cls",
",",
"qs",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"issubclass",
"(",
"cls",
",",
"QuerySet",
")",
",",
"\"%s is not a QuerySet subclass\"",
"%",
"cls",
"assert",
"isinstance",
"(",
"qs",
",",
"QuerySet",
")",
",",
"\"q... | Creates a new queryset using class `cls` using `qs'` data.
:param qs: The query set to clone
:keyword kwargs: The kwargs to pass to _clone method | [
"Creates",
"a",
"new",
"queryset",
"using",
"class",
"cls",
"using",
"qs",
"data",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/queryset.py#L774-L783 | train | 29,342 |
aparo/pyes | pyes/helpers.py | SettingsBuilder.add_mapping | def add_mapping(self, data, name=None):
"""
Add a new mapping
"""
from .mappings import DocumentObjectField
from .mappings import NestedObject
from .mappings import ObjectField
if isinstance(data, (DocumentObjectField, ObjectField, NestedObject)):
self.mappings[data.name] = data.as_dict()
return
if name:
self.mappings[name] = data
return
if isinstance(data, dict):
self.mappings.update(data)
elif isinstance(data, list):
for d in data:
if isinstance(d, dict):
self.mappings.update(d)
elif isinstance(d, DocumentObjectField):
self.mappings[d.name] = d.as_dict()
else:
name, data = d
self.add_mapping(data, name) | python | def add_mapping(self, data, name=None):
"""
Add a new mapping
"""
from .mappings import DocumentObjectField
from .mappings import NestedObject
from .mappings import ObjectField
if isinstance(data, (DocumentObjectField, ObjectField, NestedObject)):
self.mappings[data.name] = data.as_dict()
return
if name:
self.mappings[name] = data
return
if isinstance(data, dict):
self.mappings.update(data)
elif isinstance(data, list):
for d in data:
if isinstance(d, dict):
self.mappings.update(d)
elif isinstance(d, DocumentObjectField):
self.mappings[d.name] = d.as_dict()
else:
name, data = d
self.add_mapping(data, name) | [
"def",
"add_mapping",
"(",
"self",
",",
"data",
",",
"name",
"=",
"None",
")",
":",
"from",
".",
"mappings",
"import",
"DocumentObjectField",
"from",
".",
"mappings",
"import",
"NestedObject",
"from",
".",
"mappings",
"import",
"ObjectField",
"if",
"isinstance... | Add a new mapping | [
"Add",
"a",
"new",
"mapping"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/helpers.py#L11-L36 | train | 29,343 |
aparo/pyes | pyes/mappings.py | get_field | def get_field(name, data, default="object", document_object_field=None, is_document=False):
"""
Return a valid Field by given data
"""
if isinstance(data, AbstractField):
return data
data = keys_to_string(data)
_type = data.get('type', default)
if _type == "string":
return StringField(name=name, **data)
elif _type == "binary":
return BinaryField(name=name, **data)
elif _type == "boolean":
return BooleanField(name=name, **data)
elif _type == "byte":
return ByteField(name=name, **data)
elif _type == "short":
return ShortField(name=name, **data)
elif _type == "integer":
return IntegerField(name=name, **data)
elif _type == "long":
return LongField(name=name, **data)
elif _type == "float":
return FloatField(name=name, **data)
elif _type == "double":
return DoubleField(name=name, **data)
elif _type == "ip":
return IpField(name=name, **data)
elif _type == "date":
return DateField(name=name, **data)
elif _type == "multi_field":
return MultiField(name=name, **data)
elif _type == "geo_point":
return GeoPointField(name=name, **data)
elif _type == "attachment":
return AttachmentField(name=name, **data)
elif is_document or _type == "document":
if document_object_field:
return document_object_field(name=name, **data)
else:
data.pop("name",None)
return DocumentObjectField(name=name, **data)
elif _type == "object":
if '_timestamp' in data or "_all" in data:
if document_object_field:
return document_object_field(name=name, **data)
else:
return DocumentObjectField(name=name, **data)
return ObjectField(name=name, **data)
elif _type == "nested":
return NestedObject(name=name, **data)
raise RuntimeError("Invalid type: %s" % _type) | python | def get_field(name, data, default="object", document_object_field=None, is_document=False):
"""
Return a valid Field by given data
"""
if isinstance(data, AbstractField):
return data
data = keys_to_string(data)
_type = data.get('type', default)
if _type == "string":
return StringField(name=name, **data)
elif _type == "binary":
return BinaryField(name=name, **data)
elif _type == "boolean":
return BooleanField(name=name, **data)
elif _type == "byte":
return ByteField(name=name, **data)
elif _type == "short":
return ShortField(name=name, **data)
elif _type == "integer":
return IntegerField(name=name, **data)
elif _type == "long":
return LongField(name=name, **data)
elif _type == "float":
return FloatField(name=name, **data)
elif _type == "double":
return DoubleField(name=name, **data)
elif _type == "ip":
return IpField(name=name, **data)
elif _type == "date":
return DateField(name=name, **data)
elif _type == "multi_field":
return MultiField(name=name, **data)
elif _type == "geo_point":
return GeoPointField(name=name, **data)
elif _type == "attachment":
return AttachmentField(name=name, **data)
elif is_document or _type == "document":
if document_object_field:
return document_object_field(name=name, **data)
else:
data.pop("name",None)
return DocumentObjectField(name=name, **data)
elif _type == "object":
if '_timestamp' in data or "_all" in data:
if document_object_field:
return document_object_field(name=name, **data)
else:
return DocumentObjectField(name=name, **data)
return ObjectField(name=name, **data)
elif _type == "nested":
return NestedObject(name=name, **data)
raise RuntimeError("Invalid type: %s" % _type) | [
"def",
"get_field",
"(",
"name",
",",
"data",
",",
"default",
"=",
"\"object\"",
",",
"document_object_field",
"=",
"None",
",",
"is_document",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"AbstractField",
")",
":",
"return",
"data",
"data... | Return a valid Field by given data | [
"Return",
"a",
"valid",
"Field",
"by",
"given",
"data"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/mappings.py#L754-L807 | train | 29,344 |
aparo/pyes | pyes/mappings.py | ObjectField.get_properties_by_type | def get_properties_by_type(self, type, recursive=True, parent_path=""):
"""
Returns a sorted list of fields that match the type.
:param type the type of the field "string","integer" or a list of types
:param recursive recurse to sub object
:returns a sorted list of fields the match the type
"""
if parent_path:
parent_path += "."
if isinstance(type, str):
if type == "*":
type = set(MAPPING_NAME_TYPE.keys()) - set(["nested", "multi_field", "multifield"])
else:
type = [type]
properties = []
for prop in list(self.properties.values()):
if prop.type in type:
properties.append((parent_path + prop.name, prop))
continue
elif prop.type == "multi_field" and prop.name in prop.fields and prop.fields[prop.name].type in type:
properties.append((parent_path + prop.name, prop))
continue
if not recursive:
continue
if prop.type in ["nested", "object"]:
properties.extend(
prop.get_properties_by_type(type, recursive=recursive, parent_path=parent_path + prop.name))
return sorted(properties) | python | def get_properties_by_type(self, type, recursive=True, parent_path=""):
"""
Returns a sorted list of fields that match the type.
:param type the type of the field "string","integer" or a list of types
:param recursive recurse to sub object
:returns a sorted list of fields the match the type
"""
if parent_path:
parent_path += "."
if isinstance(type, str):
if type == "*":
type = set(MAPPING_NAME_TYPE.keys()) - set(["nested", "multi_field", "multifield"])
else:
type = [type]
properties = []
for prop in list(self.properties.values()):
if prop.type in type:
properties.append((parent_path + prop.name, prop))
continue
elif prop.type == "multi_field" and prop.name in prop.fields and prop.fields[prop.name].type in type:
properties.append((parent_path + prop.name, prop))
continue
if not recursive:
continue
if prop.type in ["nested", "object"]:
properties.extend(
prop.get_properties_by_type(type, recursive=recursive, parent_path=parent_path + prop.name))
return sorted(properties) | [
"def",
"get_properties_by_type",
"(",
"self",
",",
"type",
",",
"recursive",
"=",
"True",
",",
"parent_path",
"=",
"\"\"",
")",
":",
"if",
"parent_path",
":",
"parent_path",
"+=",
"\".\"",
"if",
"isinstance",
"(",
"type",
",",
"str",
")",
":",
"if",
"typ... | Returns a sorted list of fields that match the type.
:param type the type of the field "string","integer" or a list of types
:param recursive recurse to sub object
:returns a sorted list of fields the match the type | [
"Returns",
"a",
"sorted",
"list",
"of",
"fields",
"that",
"match",
"the",
"type",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/mappings.py#L489-L520 | train | 29,345 |
aparo/pyes | pyes/mappings.py | ObjectField.get_property_by_name | def get_property_by_name(self, name):
"""
Returns a mapped object.
:param name the name of the property
:returns the mapped object or exception NotFoundMapping
"""
if "." not in name and name in self.properties:
return self.properties[name]
tokens = name.split(".")
object = self
for token in tokens:
if isinstance(object, (DocumentObjectField, ObjectField, NestedObject)):
if token in object.properties:
object = object.properties[token]
continue
elif isinstance(object, MultiField):
if token in object.fields:
object = object.fields[token]
continue
raise MappedFieldNotFoundException(token)
if isinstance(object, (AbstractField, MultiField)):
return object
raise MappedFieldNotFoundException(object) | python | def get_property_by_name(self, name):
"""
Returns a mapped object.
:param name the name of the property
:returns the mapped object or exception NotFoundMapping
"""
if "." not in name and name in self.properties:
return self.properties[name]
tokens = name.split(".")
object = self
for token in tokens:
if isinstance(object, (DocumentObjectField, ObjectField, NestedObject)):
if token in object.properties:
object = object.properties[token]
continue
elif isinstance(object, MultiField):
if token in object.fields:
object = object.fields[token]
continue
raise MappedFieldNotFoundException(token)
if isinstance(object, (AbstractField, MultiField)):
return object
raise MappedFieldNotFoundException(object) | [
"def",
"get_property_by_name",
"(",
"self",
",",
"name",
")",
":",
"if",
"\".\"",
"not",
"in",
"name",
"and",
"name",
"in",
"self",
".",
"properties",
":",
"return",
"self",
".",
"properties",
"[",
"name",
"]",
"tokens",
"=",
"name",
".",
"split",
"(",... | Returns a mapped object.
:param name the name of the property
:returns the mapped object or exception NotFoundMapping | [
"Returns",
"a",
"mapped",
"object",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/mappings.py#L522-L547 | train | 29,346 |
aparo/pyes | pyes/mappings.py | ObjectField.get_available_facets | def get_available_facets(self):
"""
Returns Available facets for the document
"""
result = []
for k, v in list(self.properties.items()):
if isinstance(v, DateField):
if not v.tokenize:
result.append((k, "date"))
elif isinstance(v, NumericFieldAbstract):
result.append((k, "numeric"))
elif isinstance(v, StringField):
if not v.tokenize:
result.append((k, "term"))
elif isinstance(v, GeoPointField):
if not v.tokenize:
result.append((k, "geo"))
elif isinstance(v, ObjectField):
for n, t in self.get_available_facets():
result.append((self.name + "." + k, t))
return result | python | def get_available_facets(self):
"""
Returns Available facets for the document
"""
result = []
for k, v in list(self.properties.items()):
if isinstance(v, DateField):
if not v.tokenize:
result.append((k, "date"))
elif isinstance(v, NumericFieldAbstract):
result.append((k, "numeric"))
elif isinstance(v, StringField):
if not v.tokenize:
result.append((k, "term"))
elif isinstance(v, GeoPointField):
if not v.tokenize:
result.append((k, "geo"))
elif isinstance(v, ObjectField):
for n, t in self.get_available_facets():
result.append((self.name + "." + k, t))
return result | [
"def",
"get_available_facets",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"list",
"(",
"self",
".",
"properties",
".",
"items",
"(",
")",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"DateField",
")",
":",
"if",
"... | Returns Available facets for the document | [
"Returns",
"Available",
"facets",
"for",
"the",
"document"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/mappings.py#L550-L570 | train | 29,347 |
aparo/pyes | pyes/mappings.py | ObjectField.get_datetime_properties | def get_datetime_properties(self, recursive=True):
"""
Returns a dict of property.path and property.
:param recursive the name of the property
:returns a dict
"""
res = {}
for name, field in self.properties.items():
if isinstance(field, DateField):
res[name] = field
elif recursive and isinstance(field, ObjectField):
for n, f in field.get_datetime_properties(recursive=recursive):
res[name + "." + n] = f
return res | python | def get_datetime_properties(self, recursive=True):
"""
Returns a dict of property.path and property.
:param recursive the name of the property
:returns a dict
"""
res = {}
for name, field in self.properties.items():
if isinstance(field, DateField):
res[name] = field
elif recursive and isinstance(field, ObjectField):
for n, f in field.get_datetime_properties(recursive=recursive):
res[name + "." + n] = f
return res | [
"def",
"get_datetime_properties",
"(",
"self",
",",
"recursive",
"=",
"True",
")",
":",
"res",
"=",
"{",
"}",
"for",
"name",
",",
"field",
"in",
"self",
".",
"properties",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"field",
",",
"DateField",... | Returns a dict of property.path and property.
:param recursive the name of the property
:returns a dict | [
"Returns",
"a",
"dict",
"of",
"property",
".",
"path",
"and",
"property",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/mappings.py#L572-L587 | train | 29,348 |
aparo/pyes | pyes/mappings.py | DocumentObjectField.get_meta | def get_meta(self, subtype=None):
"""
Return the meta data.
"""
if subtype:
return DotDict(self._meta.get(subtype, {}))
return self._meta | python | def get_meta(self, subtype=None):
"""
Return the meta data.
"""
if subtype:
return DotDict(self._meta.get(subtype, {}))
return self._meta | [
"def",
"get_meta",
"(",
"self",
",",
"subtype",
"=",
"None",
")",
":",
"if",
"subtype",
":",
"return",
"DotDict",
"(",
"self",
".",
"_meta",
".",
"get",
"(",
"subtype",
",",
"{",
"}",
")",
")",
"return",
"self",
".",
"_meta"
] | Return the meta data. | [
"Return",
"the",
"meta",
"data",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/mappings.py#L680-L686 | train | 29,349 |
aparo/pyes | pyes/mappings.py | Mapper._process | def _process(self, data):
"""
Process indexer data
"""
indices = []
for indexname, indexdata in list(data.items()):
idata = []
for docname, docdata in list(indexdata.get("mappings", {}).items()):
o = get_field(docname, docdata, document_object_field=self.document_object_field, is_document=True)
o.connection = self.connection
o.index_name = indexname
idata.append((docname, o))
idata.sort()
indices.append((indexname, idata))
indices.sort()
self.indices = OrderedDict(indices) | python | def _process(self, data):
"""
Process indexer data
"""
indices = []
for indexname, indexdata in list(data.items()):
idata = []
for docname, docdata in list(indexdata.get("mappings", {}).items()):
o = get_field(docname, docdata, document_object_field=self.document_object_field, is_document=True)
o.connection = self.connection
o.index_name = indexname
idata.append((docname, o))
idata.sort()
indices.append((indexname, idata))
indices.sort()
self.indices = OrderedDict(indices) | [
"def",
"_process",
"(",
"self",
",",
"data",
")",
":",
"indices",
"=",
"[",
"]",
"for",
"indexname",
",",
"indexdata",
"in",
"list",
"(",
"data",
".",
"items",
"(",
")",
")",
":",
"idata",
"=",
"[",
"]",
"for",
"docname",
",",
"docdata",
"in",
"l... | Process indexer data | [
"Process",
"indexer",
"data"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/mappings.py#L829-L844 | train | 29,350 |
aparo/pyes | pyes/mappings.py | Mapper.get_doctypes | def get_doctypes(self, index, edges=True):
"""
Returns a list of doctypes given an index
"""
if index not in self.indices:
self.get_all_indices()
return self.indices.get(index, {}) | python | def get_doctypes(self, index, edges=True):
"""
Returns a list of doctypes given an index
"""
if index not in self.indices:
self.get_all_indices()
return self.indices.get(index, {}) | [
"def",
"get_doctypes",
"(",
"self",
",",
"index",
",",
"edges",
"=",
"True",
")",
":",
"if",
"index",
"not",
"in",
"self",
".",
"indices",
":",
"self",
".",
"get_all_indices",
"(",
")",
"return",
"self",
".",
"indices",
".",
"get",
"(",
"index",
",",... | Returns a list of doctypes given an index | [
"Returns",
"a",
"list",
"of",
"doctypes",
"given",
"an",
"index"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/mappings.py#L847-L853 | train | 29,351 |
aparo/pyes | pyes/mappings.py | Mapper.get_doctype | def get_doctype(self, index, name):
"""
Returns a doctype given an index and a name
"""
if index not in self.indices:
self.get_all_indices()
return self.indices.get(index, {}).get(name, None) | python | def get_doctype(self, index, name):
"""
Returns a doctype given an index and a name
"""
if index not in self.indices:
self.get_all_indices()
return self.indices.get(index, {}).get(name, None) | [
"def",
"get_doctype",
"(",
"self",
",",
"index",
",",
"name",
")",
":",
"if",
"index",
"not",
"in",
"self",
".",
"indices",
":",
"self",
".",
"get_all_indices",
"(",
")",
"return",
"self",
".",
"indices",
".",
"get",
"(",
"index",
",",
"{",
"}",
")... | Returns a doctype given an index and a name | [
"Returns",
"a",
"doctype",
"given",
"an",
"index",
"and",
"a",
"name"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/mappings.py#L855-L861 | train | 29,352 |
aparo/pyes | pyes/mappings.py | Mapper.get_property | def get_property(self, index, doctype, name):
"""
Returns a property of a given type
:return a mapped property
"""
return self.indices[index][doctype].properties[name] | python | def get_property(self, index, doctype, name):
"""
Returns a property of a given type
:return a mapped property
"""
return self.indices[index][doctype].properties[name] | [
"def",
"get_property",
"(",
"self",
",",
"index",
",",
"doctype",
",",
"name",
")",
":",
"return",
"self",
".",
"indices",
"[",
"index",
"]",
"[",
"doctype",
"]",
".",
"properties",
"[",
"name",
"]"
] | Returns a property of a given type
:return a mapped property | [
"Returns",
"a",
"property",
"of",
"a",
"given",
"type"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/mappings.py#L863-L870 | train | 29,353 |
aparo/pyes | pyes/mappings.py | Mapper.migrate | def migrate(self, mapping, index, doc_type):
"""
Migrate a ES mapping
:param mapping: new mapping
:param index: index of old mapping
:param doc_type: type of old mapping
:return: The diff mapping
"""
old_mapping = self.get_doctype(index, doc_type)
#case missing
if not old_mapping:
self.connection.indices.put_mapping(doc_type=doc_type, mapping=mapping, indices=index)
return mapping
# we need to calculate the diff
mapping_diff = old_mapping.get_diff(mapping)
if not mapping_diff:
return None
from pprint import pprint
pprint(mapping_diff.as_dict())
mapping_diff.connection = old_mapping.connection
mapping_diff.save() | python | def migrate(self, mapping, index, doc_type):
"""
Migrate a ES mapping
:param mapping: new mapping
:param index: index of old mapping
:param doc_type: type of old mapping
:return: The diff mapping
"""
old_mapping = self.get_doctype(index, doc_type)
#case missing
if not old_mapping:
self.connection.indices.put_mapping(doc_type=doc_type, mapping=mapping, indices=index)
return mapping
# we need to calculate the diff
mapping_diff = old_mapping.get_diff(mapping)
if not mapping_diff:
return None
from pprint import pprint
pprint(mapping_diff.as_dict())
mapping_diff.connection = old_mapping.connection
mapping_diff.save() | [
"def",
"migrate",
"(",
"self",
",",
"mapping",
",",
"index",
",",
"doc_type",
")",
":",
"old_mapping",
"=",
"self",
".",
"get_doctype",
"(",
"index",
",",
"doc_type",
")",
"#case missing",
"if",
"not",
"old_mapping",
":",
"self",
".",
"connection",
".",
... | Migrate a ES mapping
:param mapping: new mapping
:param index: index of old mapping
:param doc_type: type of old mapping
:return: The diff mapping | [
"Migrate",
"a",
"ES",
"mapping"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/mappings.py#L879-L902 | train | 29,354 |
aparo/pyes | pyes/scriptfields.py | ScriptFields.add_field | def add_field(self, name, script, lang=None, params=None, ignore_failure=False):
"""
Add a field to script_fields
"""
data = {}
if lang:
data["lang"] = lang
if script:
data['script'] = script
else:
raise ScriptFieldsError("Script is required for script_fields definition")
if params:
if isinstance(params, dict):
if len(params):
data['params'] = params
else:
raise ScriptFieldsError("Parameters should be a valid dictionary")
if ignore_failure:
data['ignore_failure'] = ignore_failure
self.fields[name] = data | python | def add_field(self, name, script, lang=None, params=None, ignore_failure=False):
"""
Add a field to script_fields
"""
data = {}
if lang:
data["lang"] = lang
if script:
data['script'] = script
else:
raise ScriptFieldsError("Script is required for script_fields definition")
if params:
if isinstance(params, dict):
if len(params):
data['params'] = params
else:
raise ScriptFieldsError("Parameters should be a valid dictionary")
if ignore_failure:
data['ignore_failure'] = ignore_failure
self.fields[name] = data | [
"def",
"add_field",
"(",
"self",
",",
"name",
",",
"script",
",",
"lang",
"=",
"None",
",",
"params",
"=",
"None",
",",
"ignore_failure",
"=",
"False",
")",
":",
"data",
"=",
"{",
"}",
"if",
"lang",
":",
"data",
"[",
"\"lang\"",
"]",
"=",
"lang",
... | Add a field to script_fields | [
"Add",
"a",
"field",
"to",
"script_fields"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/scriptfields.py#L26-L46 | train | 29,355 |
aparo/pyes | pyes/scriptfields.py | ScriptFields.add_parameter | def add_parameter(self, field_name, param_name, param_value):
"""
Add a parameter to a field into script_fields
The ScriptFields object will be returned, so calls to this can be chained.
"""
try:
self.fields[field_name]['params'][param_name] = param_value
except Exception as ex:
raise ScriptFieldsError("Error adding parameter %s with value %s :%s" % (param_name, param_value, ex))
return self | python | def add_parameter(self, field_name, param_name, param_value):
"""
Add a parameter to a field into script_fields
The ScriptFields object will be returned, so calls to this can be chained.
"""
try:
self.fields[field_name]['params'][param_name] = param_value
except Exception as ex:
raise ScriptFieldsError("Error adding parameter %s with value %s :%s" % (param_name, param_value, ex))
return self | [
"def",
"add_parameter",
"(",
"self",
",",
"field_name",
",",
"param_name",
",",
"param_value",
")",
":",
"try",
":",
"self",
".",
"fields",
"[",
"field_name",
"]",
"[",
"'params'",
"]",
"[",
"param_name",
"]",
"=",
"param_value",
"except",
"Exception",
"as... | Add a parameter to a field into script_fields
The ScriptFields object will be returned, so calls to this can be chained. | [
"Add",
"a",
"parameter",
"to",
"a",
"field",
"into",
"script_fields"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/scriptfields.py#L48-L59 | train | 29,356 |
aparo/pyes | pyes/query.py | Suggest.add | def add(self, text, name, field, type='term', size=None, params=None):
"""
Set the suggester of given type.
:param text: text
:param name: name of suggest
:param field: field to be used
:param type: type of suggester to add, available types are: completion,
phrase, term
:param size: number of phrases
:param params: dict of additional parameters to pass to the suggester
:return: None
"""
func = None
if type == 'completion':
func = self.add_completion
elif type == 'phrase':
func = self.add_phrase
elif type == 'term':
func = self.add_term
else:
raise InvalidQuery('Invalid type')
func(text=text, name=name, field=field, size=size, params=params) | python | def add(self, text, name, field, type='term', size=None, params=None):
"""
Set the suggester of given type.
:param text: text
:param name: name of suggest
:param field: field to be used
:param type: type of suggester to add, available types are: completion,
phrase, term
:param size: number of phrases
:param params: dict of additional parameters to pass to the suggester
:return: None
"""
func = None
if type == 'completion':
func = self.add_completion
elif type == 'phrase':
func = self.add_phrase
elif type == 'term':
func = self.add_term
else:
raise InvalidQuery('Invalid type')
func(text=text, name=name, field=field, size=size, params=params) | [
"def",
"add",
"(",
"self",
",",
"text",
",",
"name",
",",
"field",
",",
"type",
"=",
"'term'",
",",
"size",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"func",
"=",
"None",
"if",
"type",
"==",
"'completion'",
":",
"func",
"=",
"self",
".",... | Set the suggester of given type.
:param text: text
:param name: name of suggest
:param field: field to be used
:param type: type of suggester to add, available types are: completion,
phrase, term
:param size: number of phrases
:param params: dict of additional parameters to pass to the suggester
:return: None | [
"Set",
"the",
"suggester",
"of",
"given",
"type",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/query.py#L18-L42 | train | 29,357 |
aparo/pyes | pyes/query.py | Search.add_highlight | def add_highlight(self, field, fragment_size=None,
number_of_fragments=None, fragment_offset=None, type=None):
"""Add a highlight field.
The Search object will be returned, so calls to this can be chained.
"""
if self._highlight is None:
self._highlight = HighLighter("<b>", "</b>")
self._highlight.add_field(field, fragment_size, number_of_fragments, fragment_offset, type=type)
return self | python | def add_highlight(self, field, fragment_size=None,
number_of_fragments=None, fragment_offset=None, type=None):
"""Add a highlight field.
The Search object will be returned, so calls to this can be chained.
"""
if self._highlight is None:
self._highlight = HighLighter("<b>", "</b>")
self._highlight.add_field(field, fragment_size, number_of_fragments, fragment_offset, type=type)
return self | [
"def",
"add_highlight",
"(",
"self",
",",
"field",
",",
"fragment_size",
"=",
"None",
",",
"number_of_fragments",
"=",
"None",
",",
"fragment_offset",
"=",
"None",
",",
"type",
"=",
"None",
")",
":",
"if",
"self",
".",
"_highlight",
"is",
"None",
":",
"s... | Add a highlight field.
The Search object will be returned, so calls to this can be chained. | [
"Add",
"a",
"highlight",
"field",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/query.py#L302-L312 | train | 29,358 |
aparo/pyes | pyes/query.py | Search.add_index_boost | def add_index_boost(self, index, boost):
"""Add a boost on an index.
The Search object will be returned, so calls to this can be chained.
"""
if boost is None:
if index in self.index_boost:
del(self.index_boost[index])
else:
self.index_boost[index] = boost
return self | python | def add_index_boost(self, index, boost):
"""Add a boost on an index.
The Search object will be returned, so calls to this can be chained.
"""
if boost is None:
if index in self.index_boost:
del(self.index_boost[index])
else:
self.index_boost[index] = boost
return self | [
"def",
"add_index_boost",
"(",
"self",
",",
"index",
",",
"boost",
")",
":",
"if",
"boost",
"is",
"None",
":",
"if",
"index",
"in",
"self",
".",
"index_boost",
":",
"del",
"(",
"self",
".",
"index_boost",
"[",
"index",
"]",
")",
"else",
":",
"self",
... | Add a boost on an index.
The Search object will be returned, so calls to this can be chained. | [
"Add",
"a",
"boost",
"on",
"an",
"index",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/query.py#L314-L325 | train | 29,359 |
aparo/pyes | pyes/query.py | ConstantScoreQuery.add | def add(self, filter_or_query):
"""Add a filter, or a list of filters, to the query.
If a sequence of filters is supplied, they are all added, and will be
combined with an ANDFilter.
If a sequence of queries is supplied, they are all added, and will be
combined with an BooleanQuery(must) .
"""
if isinstance(filter_or_query, Filter):
if self.queries:
raise QueryError("A Query is required")
self.filters.append(filter_or_query)
elif isinstance(filter_or_query, Query):
if self.filters:
raise QueryError("A Filter is required")
self.queries.append(filter_or_query)
else:
for item in filter_or_query:
self.add(item)
return self | python | def add(self, filter_or_query):
"""Add a filter, or a list of filters, to the query.
If a sequence of filters is supplied, they are all added, and will be
combined with an ANDFilter.
If a sequence of queries is supplied, they are all added, and will be
combined with an BooleanQuery(must) .
"""
if isinstance(filter_or_query, Filter):
if self.queries:
raise QueryError("A Query is required")
self.filters.append(filter_or_query)
elif isinstance(filter_or_query, Query):
if self.filters:
raise QueryError("A Filter is required")
self.queries.append(filter_or_query)
else:
for item in filter_or_query:
self.add(item)
return self | [
"def",
"add",
"(",
"self",
",",
"filter_or_query",
")",
":",
"if",
"isinstance",
"(",
"filter_or_query",
",",
"Filter",
")",
":",
"if",
"self",
".",
"queries",
":",
"raise",
"QueryError",
"(",
"\"A Query is required\"",
")",
"self",
".",
"filters",
".",
"a... | Add a filter, or a list of filters, to the query.
If a sequence of filters is supplied, they are all added, and will be
combined with an ANDFilter.
If a sequence of queries is supplied, they are all added, and will be
combined with an BooleanQuery(must) . | [
"Add",
"a",
"filter",
"or",
"a",
"list",
"of",
"filters",
"to",
"the",
"query",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/query.py#L479-L500 | train | 29,360 |
aparo/pyes | performance/utils.py | get_names | def get_names():
"""
Return a list of names.
"""
return [n.strip() for n in codecs.open(os.path.join("data", "names.txt"),"rb",'utf8').readlines()] | python | def get_names():
"""
Return a list of names.
"""
return [n.strip() for n in codecs.open(os.path.join("data", "names.txt"),"rb",'utf8').readlines()] | [
"def",
"get_names",
"(",
")",
":",
"return",
"[",
"n",
".",
"strip",
"(",
")",
"for",
"n",
"in",
"codecs",
".",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"\"data\"",
",",
"\"names.txt\"",
")",
",",
"\"rb\"",
",",
"'utf8'",
")",
".",
"read... | Return a list of names. | [
"Return",
"a",
"list",
"of",
"names",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/performance/utils.py#L10-L14 | train | 29,361 |
aparo/pyes | contrib/mailman/archive_and_index.py | ext_process | def ext_process(listname, hostname, url, filepath, msg):
"""Here's where you put your code to deal with the just archived message.
Arguments here are the list name, the host name, the URL to the just
archived message, the file system path to the just archived message and
the message object.
These can be replaced or augmented as needed.
"""
from pyes import ES
from pyes.exceptions import ClusterBlockException, NoServerAvailable
import datetime
#CHANGE this settings to reflect your configuration
_ES_SERVERS = ['127.0.0.1:9500'] # I prefer thrift
_indexname = "mailman"
_doctype = "mail"
date = datetime.datetime.today()
try:
iconn = ES(_ES_SERVERS)
status = None
try:
status = iconn.status(_indexname)
logger.debug("Indexer status:%s" % status)
except:
iconn.create_index(_indexname)
time.sleep(1)
status = iconn.status(_indexname)
mappings = { u'text': {'boost': 1.0,
'index': 'analyzed',
'store': 'yes',
'type': u'string',
"term_vector" : "with_positions_offsets"},
u'url': {'boost': 1.0,
'index': 'not_analyzed',
'store': 'yes',
'type': u'string',
"term_vector" : "no"},
u'title': {'boost': 1.0,
'index': 'analyzed',
'store': 'yes',
'type': u'string',
"term_vector" : "with_positions_offsets"},
u'date': {'store': 'yes',
'type': u'date'}}
time.sleep(1)
status = iconn.put_mapping(_doctype, mappings, _indexname)
data = dict(url=url,
title=msg.get('subject'),
date=date,
text=str(msg)
)
iconn.index(data, _indexname, _doctype)
syslog('debug', 'listname: %s, hostname: %s, url: %s, path: %s, msg: %s',
listname, hostname, url, filepath, msg)
except ClusterBlockException:
syslog('error', 'Cluster in revocery state: listname: %s, hostname: %s, url: %s, path: %s, msg: %s',
listname, hostname, url, filepath, msg)
except NoServerAvailable:
syslog('error', 'No server available: listname: %s, hostname: %s, url: %s, path: %s, msg: %s',
listname, hostname, url, filepath, msg)
except:
import traceback
syslog('error', 'Unknown: listname: %s, hostname: %s, url: %s, path: %s, msg: %s\nstacktrace: %s',
listname, hostname, url, filepath, msg, repr(traceback.format_exc()))
return | python | def ext_process(listname, hostname, url, filepath, msg):
"""Here's where you put your code to deal with the just archived message.
Arguments here are the list name, the host name, the URL to the just
archived message, the file system path to the just archived message and
the message object.
These can be replaced or augmented as needed.
"""
from pyes import ES
from pyes.exceptions import ClusterBlockException, NoServerAvailable
import datetime
#CHANGE this settings to reflect your configuration
_ES_SERVERS = ['127.0.0.1:9500'] # I prefer thrift
_indexname = "mailman"
_doctype = "mail"
date = datetime.datetime.today()
try:
iconn = ES(_ES_SERVERS)
status = None
try:
status = iconn.status(_indexname)
logger.debug("Indexer status:%s" % status)
except:
iconn.create_index(_indexname)
time.sleep(1)
status = iconn.status(_indexname)
mappings = { u'text': {'boost': 1.0,
'index': 'analyzed',
'store': 'yes',
'type': u'string',
"term_vector" : "with_positions_offsets"},
u'url': {'boost': 1.0,
'index': 'not_analyzed',
'store': 'yes',
'type': u'string',
"term_vector" : "no"},
u'title': {'boost': 1.0,
'index': 'analyzed',
'store': 'yes',
'type': u'string',
"term_vector" : "with_positions_offsets"},
u'date': {'store': 'yes',
'type': u'date'}}
time.sleep(1)
status = iconn.put_mapping(_doctype, mappings, _indexname)
data = dict(url=url,
title=msg.get('subject'),
date=date,
text=str(msg)
)
iconn.index(data, _indexname, _doctype)
syslog('debug', 'listname: %s, hostname: %s, url: %s, path: %s, msg: %s',
listname, hostname, url, filepath, msg)
except ClusterBlockException:
syslog('error', 'Cluster in revocery state: listname: %s, hostname: %s, url: %s, path: %s, msg: %s',
listname, hostname, url, filepath, msg)
except NoServerAvailable:
syslog('error', 'No server available: listname: %s, hostname: %s, url: %s, path: %s, msg: %s',
listname, hostname, url, filepath, msg)
except:
import traceback
syslog('error', 'Unknown: listname: %s, hostname: %s, url: %s, path: %s, msg: %s\nstacktrace: %s',
listname, hostname, url, filepath, msg, repr(traceback.format_exc()))
return | [
"def",
"ext_process",
"(",
"listname",
",",
"hostname",
",",
"url",
",",
"filepath",
",",
"msg",
")",
":",
"from",
"pyes",
"import",
"ES",
"from",
"pyes",
".",
"exceptions",
"import",
"ClusterBlockException",
",",
"NoServerAvailable",
"import",
"datetime",
"#C... | Here's where you put your code to deal with the just archived message.
Arguments here are the list name, the host name, the URL to the just
archived message, the file system path to the just archived message and
the message object.
These can be replaced or augmented as needed. | [
"Here",
"s",
"where",
"you",
"put",
"your",
"code",
"to",
"deal",
"with",
"the",
"just",
"archived",
"message",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/contrib/mailman/archive_and_index.py#L54-L124 | train | 29,362 |
aparo/pyes | contrib/mailman/archive_and_index.py | main | def main():
"""This is the mainline.
It first invokes the pipermail archiver to add the message to the archive,
then calls the function above to do whatever with the archived message
after it's URL and path are known.
"""
listname = sys.argv[2]
hostname = sys.argv[1]
# We must get the list unlocked here because it is already locked in
# ArchRunner. This is safe because we aren't actually changing our list
# object. ArchRunner's lock plus pipermail's archive lock will prevent
# any race conditions.
mlist = MailList.MailList(listname, lock=False)
# We need a seekable file for processUnixMailbox()
f = StringIO(sys.stdin.read())
# If we don't need a Message.Message instance, we can skip the next and
# the imports of email and Message above.
msg = email.message_from_file(f, Message.Message)
h = HyperArch.HyperArchive(mlist)
# Get the message number for the next message
sequence = h.sequence
# and add the message.
h.processUnixMailbox(f)
f.close()
# Get the archive name, etc.
archive = h.archive
msgno = '%06d' % sequence
filename = msgno + '.html'
filepath = os.path.join(h.basedir, archive, filename)
h.close()
url = '%s%s/%s' % (mlist.GetBaseArchiveURL(), archive, filename)
ext_process(listname, hostname, url, filepath, msg) | python | def main():
"""This is the mainline.
It first invokes the pipermail archiver to add the message to the archive,
then calls the function above to do whatever with the archived message
after it's URL and path are known.
"""
listname = sys.argv[2]
hostname = sys.argv[1]
# We must get the list unlocked here because it is already locked in
# ArchRunner. This is safe because we aren't actually changing our list
# object. ArchRunner's lock plus pipermail's archive lock will prevent
# any race conditions.
mlist = MailList.MailList(listname, lock=False)
# We need a seekable file for processUnixMailbox()
f = StringIO(sys.stdin.read())
# If we don't need a Message.Message instance, we can skip the next and
# the imports of email and Message above.
msg = email.message_from_file(f, Message.Message)
h = HyperArch.HyperArchive(mlist)
# Get the message number for the next message
sequence = h.sequence
# and add the message.
h.processUnixMailbox(f)
f.close()
# Get the archive name, etc.
archive = h.archive
msgno = '%06d' % sequence
filename = msgno + '.html'
filepath = os.path.join(h.basedir, archive, filename)
h.close()
url = '%s%s/%s' % (mlist.GetBaseArchiveURL(), archive, filename)
ext_process(listname, hostname, url, filepath, msg) | [
"def",
"main",
"(",
")",
":",
"listname",
"=",
"sys",
".",
"argv",
"[",
"2",
"]",
"hostname",
"=",
"sys",
".",
"argv",
"[",
"1",
"]",
"# We must get the list unlocked here because it is already locked in",
"# ArchRunner. This is safe because we aren't actually changing ou... | This is the mainline.
It first invokes the pipermail archiver to add the message to the archive,
then calls the function above to do whatever with the archived message
after it's URL and path are known. | [
"This",
"is",
"the",
"mainline",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/contrib/mailman/archive_and_index.py#L126-L166 | train | 29,363 |
aparo/pyes | pyes/utils/__init__.py | make_path | def make_path(*path_components):
"""
Smash together the path components. Empty components will be ignored.
"""
path_components = [quote(component) for component in path_components if component]
path = '/'.join(path_components)
if not path.startswith('/'):
path = '/' + path
return path | python | def make_path(*path_components):
"""
Smash together the path components. Empty components will be ignored.
"""
path_components = [quote(component) for component in path_components if component]
path = '/'.join(path_components)
if not path.startswith('/'):
path = '/' + path
return path | [
"def",
"make_path",
"(",
"*",
"path_components",
")",
":",
"path_components",
"=",
"[",
"quote",
"(",
"component",
")",
"for",
"component",
"in",
"path_components",
"if",
"component",
"]",
"path",
"=",
"'/'",
".",
"join",
"(",
"path_components",
")",
"if",
... | Smash together the path components. Empty components will be ignored. | [
"Smash",
"together",
"the",
"path",
"components",
".",
"Empty",
"components",
"will",
"be",
"ignored",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/utils/__init__.py#L47-L55 | train | 29,364 |
aparo/pyes | pyes/utils/__init__.py | clean_string | def clean_string(text):
"""
Remove Lucene reserved characters from query string
"""
if isinstance(text, six.string_types):
return text.translate(UNI_SPECIAL_CHARS).strip()
return text.translate(None, STR_SPECIAL_CHARS).strip() | python | def clean_string(text):
"""
Remove Lucene reserved characters from query string
"""
if isinstance(text, six.string_types):
return text.translate(UNI_SPECIAL_CHARS).strip()
return text.translate(None, STR_SPECIAL_CHARS).strip() | [
"def",
"clean_string",
"(",
"text",
")",
":",
"if",
"isinstance",
"(",
"text",
",",
"six",
".",
"string_types",
")",
":",
"return",
"text",
".",
"translate",
"(",
"UNI_SPECIAL_CHARS",
")",
".",
"strip",
"(",
")",
"return",
"text",
".",
"translate",
"(",
... | Remove Lucene reserved characters from query string | [
"Remove",
"Lucene",
"reserved",
"characters",
"from",
"query",
"string"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/utils/__init__.py#L162-L168 | train | 29,365 |
aparo/pyes | pyes/utils/__init__.py | keys_to_string | def keys_to_string(data):
"""
Function to convert all the unicode keys in string keys
"""
if isinstance(data, dict):
for key in list(data.keys()):
if isinstance(key, six.string_types):
value = data[key]
val = keys_to_string(value)
del data[key]
data[key.encode("utf8", "ignore")] = val
return data | python | def keys_to_string(data):
"""
Function to convert all the unicode keys in string keys
"""
if isinstance(data, dict):
for key in list(data.keys()):
if isinstance(key, six.string_types):
value = data[key]
val = keys_to_string(value)
del data[key]
data[key.encode("utf8", "ignore")] = val
return data | [
"def",
"keys_to_string",
"(",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"for",
"key",
"in",
"list",
"(",
"data",
".",
"keys",
"(",
")",
")",
":",
"if",
"isinstance",
"(",
"key",
",",
"six",
".",
"string_types",
")",
... | Function to convert all the unicode keys in string keys | [
"Function",
"to",
"convert",
"all",
"the",
"unicode",
"keys",
"in",
"string",
"keys"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/utils/__init__.py#L171-L182 | train | 29,366 |
aparo/pyes | pyes/utils/__init__.py | ESRange.negate | def negate(self):
"""Reverse the range"""
self.from_value, self.to_value = self.to_value, self.from_value
self.include_lower, self.include_upper = self.include_upper, self.include_lower | python | def negate(self):
"""Reverse the range"""
self.from_value, self.to_value = self.to_value, self.from_value
self.include_lower, self.include_upper = self.include_upper, self.include_lower | [
"def",
"negate",
"(",
"self",
")",
":",
"self",
".",
"from_value",
",",
"self",
".",
"to_value",
"=",
"self",
".",
"to_value",
",",
"self",
".",
"from_value",
"self",
".",
"include_lower",
",",
"self",
".",
"include_upper",
"=",
"self",
".",
"include_upp... | Reverse the range | [
"Reverse",
"the",
"range"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/utils/__init__.py#L103-L106 | train | 29,367 |
aparo/pyes | pyes/convert_errors.py | raise_if_error | def raise_if_error(status, result, request=None):
"""Raise an appropriate exception if the result is an error.
Any result with a status code of 400 or higher is considered an error.
The exception raised will either be an ElasticSearchException, or a more
specific subclass of ElasticSearchException if the type is recognised.
The status code and result can be retrieved from the exception by accessing its
status and result properties.
Optionally, this can take the original RestRequest instance which generated
this error, which will then get included in the exception.
"""
assert isinstance(status, int)
if status < 400:
return
if status == 404 and isinstance(result, dict) and 'error' not in result:
raise exceptions.NotFoundException("Item not found", status, result, request)
if not isinstance(result, dict) or 'error' not in result:
raise exceptions.ElasticSearchException("Unknown exception type: %d, %s" % (status, result), status,
result, request)
error = result['error']
if '; nested: ' in error:
error_list = error.split('; nested: ')
error = error_list[len(error_list) - 1]
bits = error.split('[', 1)
if len(bits) == 2:
excClass = exceptions_by_name.get(bits[0], None)
if excClass is not None:
msg = bits[1]
if msg.endswith(']'):
msg = msg[:-1]
'''
if request:
msg += ' (' + str(request) + ')'
'''
raise excClass(msg, status, result, request)
for pattern, excClass in list(exception_patterns_trailing.items()):
if not error.endswith(pattern):
continue
# For these exceptions, the returned value is the whole descriptive
# message.
raise excClass(error, status, result, request)
raise exceptions.ElasticSearchException(error, status, result, request) | python | def raise_if_error(status, result, request=None):
"""Raise an appropriate exception if the result is an error.
Any result with a status code of 400 or higher is considered an error.
The exception raised will either be an ElasticSearchException, or a more
specific subclass of ElasticSearchException if the type is recognised.
The status code and result can be retrieved from the exception by accessing its
status and result properties.
Optionally, this can take the original RestRequest instance which generated
this error, which will then get included in the exception.
"""
assert isinstance(status, int)
if status < 400:
return
if status == 404 and isinstance(result, dict) and 'error' not in result:
raise exceptions.NotFoundException("Item not found", status, result, request)
if not isinstance(result, dict) or 'error' not in result:
raise exceptions.ElasticSearchException("Unknown exception type: %d, %s" % (status, result), status,
result, request)
error = result['error']
if '; nested: ' in error:
error_list = error.split('; nested: ')
error = error_list[len(error_list) - 1]
bits = error.split('[', 1)
if len(bits) == 2:
excClass = exceptions_by_name.get(bits[0], None)
if excClass is not None:
msg = bits[1]
if msg.endswith(']'):
msg = msg[:-1]
'''
if request:
msg += ' (' + str(request) + ')'
'''
raise excClass(msg, status, result, request)
for pattern, excClass in list(exception_patterns_trailing.items()):
if not error.endswith(pattern):
continue
# For these exceptions, the returned value is the whole descriptive
# message.
raise excClass(error, status, result, request)
raise exceptions.ElasticSearchException(error, status, result, request) | [
"def",
"raise_if_error",
"(",
"status",
",",
"result",
",",
"request",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"status",
",",
"int",
")",
"if",
"status",
"<",
"400",
":",
"return",
"if",
"status",
"==",
"404",
"and",
"isinstance",
"(",
"res... | Raise an appropriate exception if the result is an error.
Any result with a status code of 400 or higher is considered an error.
The exception raised will either be an ElasticSearchException, or a more
specific subclass of ElasticSearchException if the type is recognised.
The status code and result can be retrieved from the exception by accessing its
status and result properties.
Optionally, this can take the original RestRequest instance which generated
this error, which will then get included in the exception. | [
"Raise",
"an",
"appropriate",
"exception",
"if",
"the",
"result",
"is",
"an",
"error",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/convert_errors.py#L42-L94 | train | 29,368 |
aparo/pyes | pyes/orm/queryset.py | QuerySet._django_to_es_field | def _django_to_es_field(self, field):
"""We use this function in value_list and ordering to get the correct fields name"""
from django.db import models
prefix = ""
if field.startswith("-"):
prefix = "-"
field = field.lstrip("-")
if field in ["id", "pk"]:
return "_id", models.AutoField
try:
dj_field, _, _, _ = self.model._meta.get_field_by_name(field)
if isinstance(dj_field, models.ForeignKey):
return prefix + field + "_id", models.ForeignKey
else:
return prefix + field, dj_field
except models.FieldDoesNotExist:
pass
return prefix + field.replace(FIELD_SEPARATOR, "."), None | python | def _django_to_es_field(self, field):
"""We use this function in value_list and ordering to get the correct fields name"""
from django.db import models
prefix = ""
if field.startswith("-"):
prefix = "-"
field = field.lstrip("-")
if field in ["id", "pk"]:
return "_id", models.AutoField
try:
dj_field, _, _, _ = self.model._meta.get_field_by_name(field)
if isinstance(dj_field, models.ForeignKey):
return prefix + field + "_id", models.ForeignKey
else:
return prefix + field, dj_field
except models.FieldDoesNotExist:
pass
return prefix + field.replace(FIELD_SEPARATOR, "."), None | [
"def",
"_django_to_es_field",
"(",
"self",
",",
"field",
")",
":",
"from",
"django",
".",
"db",
"import",
"models",
"prefix",
"=",
"\"\"",
"if",
"field",
".",
"startswith",
"(",
"\"-\"",
")",
":",
"prefix",
"=",
"\"-\"",
"field",
"=",
"field",
".",
"ls... | We use this function in value_list and ordering to get the correct fields name | [
"We",
"use",
"this",
"function",
"in",
"value_list",
"and",
"ordering",
"to",
"get",
"the",
"correct",
"fields",
"name"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/orm/queryset.py#L539-L560 | train | 29,369 |
aparo/pyes | pyes/orm/queryset.py | QuerySet.none | def none(self):
"""
Returns an empty QuerySet.
"""
return EmptyQuerySet(model=self.model, using=self._using, connection=self._connection) | python | def none(self):
"""
Returns an empty QuerySet.
"""
return EmptyQuerySet(model=self.model, using=self._using, connection=self._connection) | [
"def",
"none",
"(",
"self",
")",
":",
"return",
"EmptyQuerySet",
"(",
"model",
"=",
"self",
".",
"model",
",",
"using",
"=",
"self",
".",
"_using",
",",
"connection",
"=",
"self",
".",
"_connection",
")"
] | Returns an empty QuerySet. | [
"Returns",
"an",
"empty",
"QuerySet",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/orm/queryset.py#L643-L647 | train | 29,370 |
aparo/pyes | pyes/orm/queryset.py | QuerySet.rescorer | def rescorer(self, rescorer):
"""
Returns a new QuerySet with a set rescorer.
"""
clone = self._clone()
clone._rescorer=rescorer
return clone | python | def rescorer(self, rescorer):
"""
Returns a new QuerySet with a set rescorer.
"""
clone = self._clone()
clone._rescorer=rescorer
return clone | [
"def",
"rescorer",
"(",
"self",
",",
"rescorer",
")",
":",
"clone",
"=",
"self",
".",
"_clone",
"(",
")",
"clone",
".",
"_rescorer",
"=",
"rescorer",
"return",
"clone"
] | Returns a new QuerySet with a set rescorer. | [
"Returns",
"a",
"new",
"QuerySet",
"with",
"a",
"set",
"rescorer",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/orm/queryset.py#L685-L691 | train | 29,371 |
aparo/pyes | pyes/orm/queryset.py | QuerySet._get_filter_modifier | def _get_filter_modifier(self, field):
"""Detect the filter modifier"""
tokens = field.split(FIELD_SEPARATOR)
if len(tokens) == 1:
return field, ""
if tokens[-1] in self.FILTER_OPERATORS.keys():
return u'.'.join(tokens[:-1]), tokens[-1]
return u'.'.join(tokens), "" | python | def _get_filter_modifier(self, field):
"""Detect the filter modifier"""
tokens = field.split(FIELD_SEPARATOR)
if len(tokens) == 1:
return field, ""
if tokens[-1] in self.FILTER_OPERATORS.keys():
return u'.'.join(tokens[:-1]), tokens[-1]
return u'.'.join(tokens), "" | [
"def",
"_get_filter_modifier",
"(",
"self",
",",
"field",
")",
":",
"tokens",
"=",
"field",
".",
"split",
"(",
"FIELD_SEPARATOR",
")",
"if",
"len",
"(",
"tokens",
")",
"==",
"1",
":",
"return",
"field",
",",
"\"\"",
"if",
"tokens",
"[",
"-",
"1",
"]"... | Detect the filter modifier | [
"Detect",
"the",
"filter",
"modifier"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/orm/queryset.py#L747-L754 | train | 29,372 |
aparo/pyes | pyes/orm/queryset.py | QuerySet._prepare_value | def _prepare_value(self, value, dj_field=None):
"""Cook the value"""
from django.db import models
if isinstance(value, (six.string_types, int, float)):
return value
elif isinstance(value, SimpleLazyObject):
return value.pk
elif isinstance(value, models.Model):
if dj_field:
if isinstance(dj_field, models.ForeignKey):
return value.pk
#TODO validate other types
return value
elif isinstance(value, (ResultSet, EmptyQuerySet, EmptyResultSet, list)):
return [self._prepare_value(v, dj_field=dj_field) for v in value]
elif isinstance(value, QuerySet):
value = value._clone()
return [self._prepare_value(v, dj_field=dj_field) for v in value]
return value | python | def _prepare_value(self, value, dj_field=None):
"""Cook the value"""
from django.db import models
if isinstance(value, (six.string_types, int, float)):
return value
elif isinstance(value, SimpleLazyObject):
return value.pk
elif isinstance(value, models.Model):
if dj_field:
if isinstance(dj_field, models.ForeignKey):
return value.pk
#TODO validate other types
return value
elif isinstance(value, (ResultSet, EmptyQuerySet, EmptyResultSet, list)):
return [self._prepare_value(v, dj_field=dj_field) for v in value]
elif isinstance(value, QuerySet):
value = value._clone()
return [self._prepare_value(v, dj_field=dj_field) for v in value]
return value | [
"def",
"_prepare_value",
"(",
"self",
",",
"value",
",",
"dj_field",
"=",
"None",
")",
":",
"from",
"django",
".",
"db",
"import",
"models",
"if",
"isinstance",
"(",
"value",
",",
"(",
"six",
".",
"string_types",
",",
"int",
",",
"float",
")",
")",
"... | Cook the value | [
"Cook",
"the",
"value"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/orm/queryset.py#L756-L775 | train | 29,373 |
aparo/pyes | pyes/orm/queryset.py | QuerySet.order_by | def order_by(self, *field_names):
"""
Returns a new QuerySet instance with the ordering changed.
We have a special field "_random"
"""
obj = self._clone()
obj._clear_ordering()
self._insert_ordering(obj, *field_names)
return obj | python | def order_by(self, *field_names):
"""
Returns a new QuerySet instance with the ordering changed.
We have a special field "_random"
"""
obj = self._clone()
obj._clear_ordering()
self._insert_ordering(obj, *field_names)
return obj | [
"def",
"order_by",
"(",
"self",
",",
"*",
"field_names",
")",
":",
"obj",
"=",
"self",
".",
"_clone",
"(",
")",
"obj",
".",
"_clear_ordering",
"(",
")",
"self",
".",
"_insert_ordering",
"(",
"obj",
",",
"*",
"field_names",
")",
"return",
"obj"
] | Returns a new QuerySet instance with the ordering changed.
We have a special field "_random" | [
"Returns",
"a",
"new",
"QuerySet",
"instance",
"with",
"the",
"ordering",
"changed",
".",
"We",
"have",
"a",
"special",
"field",
"_random"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/orm/queryset.py#L1065-L1073 | train | 29,374 |
aparo/pyes | pyes/orm/queryset.py | QuerySet.index | def index(self, alias):
"""
Selects which database this QuerySet should execute its query against.
"""
clone = self._clone()
clone._index = alias
return clone | python | def index(self, alias):
"""
Selects which database this QuerySet should execute its query against.
"""
clone = self._clone()
clone._index = alias
return clone | [
"def",
"index",
"(",
"self",
",",
"alias",
")",
":",
"clone",
"=",
"self",
".",
"_clone",
"(",
")",
"clone",
".",
"_index",
"=",
"alias",
"return",
"clone"
] | Selects which database this QuerySet should execute its query against. | [
"Selects",
"which",
"database",
"this",
"QuerySet",
"should",
"execute",
"its",
"query",
"against",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/orm/queryset.py#L1150-L1156 | train | 29,375 |
aparo/pyes | pyes/orm/queryset.py | QuerySet.size | def size(self, size):
"""
Set the query size of this QuerySet should execute its query against.
"""
clone = self._clone()
clone._size = size
return clone | python | def size(self, size):
"""
Set the query size of this QuerySet should execute its query against.
"""
clone = self._clone()
clone._size = size
return clone | [
"def",
"size",
"(",
"self",
",",
"size",
")",
":",
"clone",
"=",
"self",
".",
"_clone",
"(",
")",
"clone",
".",
"_size",
"=",
"size",
"return",
"clone"
] | Set the query size of this QuerySet should execute its query against. | [
"Set",
"the",
"query",
"size",
"of",
"this",
"QuerySet",
"should",
"execute",
"its",
"query",
"against",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/orm/queryset.py#L1158-L1164 | train | 29,376 |
aparo/pyes | pyes/orm/queryset.py | QuerySet.refresh | def refresh(self):
"""Refresh an index"""
connection = self.model._meta.dj_connection
return connection.connection.indices.refresh(indices=connection.database) | python | def refresh(self):
"""Refresh an index"""
connection = self.model._meta.dj_connection
return connection.connection.indices.refresh(indices=connection.database) | [
"def",
"refresh",
"(",
"self",
")",
":",
"connection",
"=",
"self",
".",
"model",
".",
"_meta",
".",
"dj_connection",
"return",
"connection",
".",
"connection",
".",
"indices",
".",
"refresh",
"(",
"indices",
"=",
"connection",
".",
"database",
")"
] | Refresh an index | [
"Refresh",
"an",
"index"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/orm/queryset.py#L1379-L1382 | train | 29,377 |
aparo/pyes | pyes/managers.py | Indices.create_index_if_missing | def create_index_if_missing(self, index, settings=None):
"""Creates an index if it doesn't already exist.
If supplied, settings must be a dictionary.
:param index: the name of the index
:keyword settings: a settings object or a dict containing settings
"""
try:
return self.create_index(index, settings)
except IndexAlreadyExistsException as e:
return e.result | python | def create_index_if_missing(self, index, settings=None):
"""Creates an index if it doesn't already exist.
If supplied, settings must be a dictionary.
:param index: the name of the index
:keyword settings: a settings object or a dict containing settings
"""
try:
return self.create_index(index, settings)
except IndexAlreadyExistsException as e:
return e.result | [
"def",
"create_index_if_missing",
"(",
"self",
",",
"index",
",",
"settings",
"=",
"None",
")",
":",
"try",
":",
"return",
"self",
".",
"create_index",
"(",
"index",
",",
"settings",
")",
"except",
"IndexAlreadyExistsException",
"as",
"e",
":",
"return",
"e"... | Creates an index if it doesn't already exist.
If supplied, settings must be a dictionary.
:param index: the name of the index
:keyword settings: a settings object or a dict containing settings | [
"Creates",
"an",
"index",
"if",
"it",
"doesn",
"t",
"already",
"exist",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/managers.py#L167-L178 | train | 29,378 |
aparo/pyes | pyes/managers.py | Indices.get_indices | def get_indices(self, include_aliases=False):
"""
Get a dict holding an entry for each index which exists.
If include_alises is True, the dict will also contain entries for
aliases.
The key for each entry in the dict is the index or alias name. The
value is a dict holding the following properties:
- num_docs: Number of documents in the index or alias.
- alias_for: Only present for an alias: holds a list of indices which
this is an alias for.
"""
state = self.conn.cluster.state()
status = self.status()
result = {}
indices_status = status['indices']
indices_metadata = state['metadata']['indices']
for index in sorted(indices_status.keys()):
info = indices_status[index]
try:
num_docs = info['docs']['num_docs']
except KeyError:
num_docs = 0
result[index] = dict(num_docs=num_docs)
if not include_aliases:
continue
try:
metadata = indices_metadata[index]
except KeyError:
continue
for alias in metadata.get('aliases', []):
try:
alias_obj = result[alias]
except KeyError:
alias_obj = {}
result[alias] = alias_obj
alias_obj['num_docs'] = alias_obj.get('num_docs', 0) + num_docs
try:
alias_obj['alias_for'].append(index)
except KeyError:
alias_obj['alias_for'] = [index]
return result | python | def get_indices(self, include_aliases=False):
"""
Get a dict holding an entry for each index which exists.
If include_alises is True, the dict will also contain entries for
aliases.
The key for each entry in the dict is the index or alias name. The
value is a dict holding the following properties:
- num_docs: Number of documents in the index or alias.
- alias_for: Only present for an alias: holds a list of indices which
this is an alias for.
"""
state = self.conn.cluster.state()
status = self.status()
result = {}
indices_status = status['indices']
indices_metadata = state['metadata']['indices']
for index in sorted(indices_status.keys()):
info = indices_status[index]
try:
num_docs = info['docs']['num_docs']
except KeyError:
num_docs = 0
result[index] = dict(num_docs=num_docs)
if not include_aliases:
continue
try:
metadata = indices_metadata[index]
except KeyError:
continue
for alias in metadata.get('aliases', []):
try:
alias_obj = result[alias]
except KeyError:
alias_obj = {}
result[alias] = alias_obj
alias_obj['num_docs'] = alias_obj.get('num_docs', 0) + num_docs
try:
alias_obj['alias_for'].append(index)
except KeyError:
alias_obj['alias_for'] = [index]
return result | [
"def",
"get_indices",
"(",
"self",
",",
"include_aliases",
"=",
"False",
")",
":",
"state",
"=",
"self",
".",
"conn",
".",
"cluster",
".",
"state",
"(",
")",
"status",
"=",
"self",
".",
"status",
"(",
")",
"result",
"=",
"{",
"}",
"indices_status",
"... | Get a dict holding an entry for each index which exists.
If include_alises is True, the dict will also contain entries for
aliases.
The key for each entry in the dict is the index or alias name. The
value is a dict holding the following properties:
- num_docs: Number of documents in the index or alias.
- alias_for: Only present for an alias: holds a list of indices which
this is an alias for. | [
"Get",
"a",
"dict",
"holding",
"an",
"entry",
"for",
"each",
"index",
"which",
"exists",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/managers.py#L209-L254 | train | 29,379 |
aparo/pyes | pyes/managers.py | Indices.get_closed_indices | def get_closed_indices(self):
"""
Get all closed indices.
"""
state = self.conn.cluster.state()
status = self.status()
indices_metadata = set(state['metadata']['indices'].keys())
indices_status = set(status['indices'].keys())
return indices_metadata.difference(indices_status) | python | def get_closed_indices(self):
"""
Get all closed indices.
"""
state = self.conn.cluster.state()
status = self.status()
indices_metadata = set(state['metadata']['indices'].keys())
indices_status = set(status['indices'].keys())
return indices_metadata.difference(indices_status) | [
"def",
"get_closed_indices",
"(",
"self",
")",
":",
"state",
"=",
"self",
".",
"conn",
".",
"cluster",
".",
"state",
"(",
")",
"status",
"=",
"self",
".",
"status",
"(",
")",
"indices_metadata",
"=",
"set",
"(",
"state",
"[",
"'metadata'",
"]",
"[",
... | Get all closed indices. | [
"Get",
"all",
"closed",
"indices",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/managers.py#L256-L266 | train | 29,380 |
aparo/pyes | pyes/managers.py | Indices.analyze | def analyze(self, text, index=None, analyzer=None, tokenizer=None, filters=None, field=None):
"""
Performs the analysis process on a text and return the tokens breakdown of the text
(See :ref:`es-guide-reference-api-admin-indices-optimize`)
"""
if filters is None:
filters = []
argsets = 0
args = {}
if analyzer:
args['analyzer'] = analyzer
argsets += 1
if tokenizer or filters:
if tokenizer:
args['tokenizer'] = tokenizer
if filters:
args['filters'] = ','.join(filters)
argsets += 1
if field:
args['field'] = field
argsets += 1
if argsets > 1:
raise ValueError('Argument conflict: Specify either analyzer, tokenizer/filters or field')
if field and index is None:
raise ValueError('field can only be specified with an index')
path = make_path(index, '_analyze')
return self.conn._send_request('POST', path, text, args) | python | def analyze(self, text, index=None, analyzer=None, tokenizer=None, filters=None, field=None):
"""
Performs the analysis process on a text and return the tokens breakdown of the text
(See :ref:`es-guide-reference-api-admin-indices-optimize`)
"""
if filters is None:
filters = []
argsets = 0
args = {}
if analyzer:
args['analyzer'] = analyzer
argsets += 1
if tokenizer or filters:
if tokenizer:
args['tokenizer'] = tokenizer
if filters:
args['filters'] = ','.join(filters)
argsets += 1
if field:
args['field'] = field
argsets += 1
if argsets > 1:
raise ValueError('Argument conflict: Specify either analyzer, tokenizer/filters or field')
if field and index is None:
raise ValueError('field can only be specified with an index')
path = make_path(index, '_analyze')
return self.conn._send_request('POST', path, text, args) | [
"def",
"analyze",
"(",
"self",
",",
"text",
",",
"index",
"=",
"None",
",",
"analyzer",
"=",
"None",
",",
"tokenizer",
"=",
"None",
",",
"filters",
"=",
"None",
",",
"field",
"=",
"None",
")",
":",
"if",
"filters",
"is",
"None",
":",
"filters",
"="... | Performs the analysis process on a text and return the tokens breakdown of the text
(See :ref:`es-guide-reference-api-admin-indices-optimize`) | [
"Performs",
"the",
"analysis",
"process",
"on",
"a",
"text",
"and",
"return",
"the",
"tokens",
"breakdown",
"of",
"the",
"text"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/managers.py#L372-L404 | train | 29,381 |
aparo/pyes | pyes/models.py | ElasticSearchModel.save | def save(self, bulk=False, id=None, parent=None, routing=None, force=False):
"""
Save the object and returns id
"""
meta = self._meta
conn = meta['connection']
id = id or meta.get("id", None)
parent = parent or meta.get('parent', None)
routing = routing or meta.get('routing', None)
qargs = None
if routing:
qargs={'routing': routing}
version = meta.get('version', None)
if force:
version = None
res = conn.index(self,
meta.index, meta.type, id, parent=parent, bulk=bulk,
version=version, force_insert=force,
querystring_args=qargs)
if not bulk:
self._meta.id = res._id
self._meta.version = res._version
return res._id
return id | python | def save(self, bulk=False, id=None, parent=None, routing=None, force=False):
"""
Save the object and returns id
"""
meta = self._meta
conn = meta['connection']
id = id or meta.get("id", None)
parent = parent or meta.get('parent', None)
routing = routing or meta.get('routing', None)
qargs = None
if routing:
qargs={'routing': routing}
version = meta.get('version', None)
if force:
version = None
res = conn.index(self,
meta.index, meta.type, id, parent=parent, bulk=bulk,
version=version, force_insert=force,
querystring_args=qargs)
if not bulk:
self._meta.id = res._id
self._meta.version = res._version
return res._id
return id | [
"def",
"save",
"(",
"self",
",",
"bulk",
"=",
"False",
",",
"id",
"=",
"None",
",",
"parent",
"=",
"None",
",",
"routing",
"=",
"None",
",",
"force",
"=",
"False",
")",
":",
"meta",
"=",
"self",
".",
"_meta",
"conn",
"=",
"meta",
"[",
"'connectio... | Save the object and returns id | [
"Save",
"the",
"object",
"and",
"returns",
"id"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/models.py#L66-L89 | train | 29,382 |
aparo/pyes | pyes/models.py | ElasticSearchModel.get_id | def get_id(self):
""" Force the object saveing to get an id"""
_id = self._meta.get("id", None)
if _id is None:
_id = self.save()
return _id | python | def get_id(self):
""" Force the object saveing to get an id"""
_id = self._meta.get("id", None)
if _id is None:
_id = self.save()
return _id | [
"def",
"get_id",
"(",
"self",
")",
":",
"_id",
"=",
"self",
".",
"_meta",
".",
"get",
"(",
"\"id\"",
",",
"None",
")",
"if",
"_id",
"is",
"None",
":",
"_id",
"=",
"self",
".",
"save",
"(",
")",
"return",
"_id"
] | Force the object saveing to get an id | [
"Force",
"the",
"object",
"saveing",
"to",
"get",
"an",
"id"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/models.py#L98-L103 | train | 29,383 |
aparo/pyes | pyes/models.py | ElasticSearchModel.get_bulk | def get_bulk(self, create=False):
"""Return bulk code"""
result = []
op_type = "index"
if create:
op_type = "create"
meta = self._meta
cmd = {op_type: {"_index": meta.index, "_type": meta.type}}
if meta.parent:
cmd[op_type]['_parent'] = meta.parent
if meta.version:
cmd[op_type]['_version'] = meta.version
if meta.id:
cmd[op_type]['_id'] = meta.id
result.append(json.dumps(cmd, cls=self._meta.connection.encoder))
result.append("\n")
result.append(json.dumps(self, cls=self._meta.connection.encoder))
result.append("\n")
return ''.join(result) | python | def get_bulk(self, create=False):
"""Return bulk code"""
result = []
op_type = "index"
if create:
op_type = "create"
meta = self._meta
cmd = {op_type: {"_index": meta.index, "_type": meta.type}}
if meta.parent:
cmd[op_type]['_parent'] = meta.parent
if meta.version:
cmd[op_type]['_version'] = meta.version
if meta.id:
cmd[op_type]['_id'] = meta.id
result.append(json.dumps(cmd, cls=self._meta.connection.encoder))
result.append("\n")
result.append(json.dumps(self, cls=self._meta.connection.encoder))
result.append("\n")
return ''.join(result) | [
"def",
"get_bulk",
"(",
"self",
",",
"create",
"=",
"False",
")",
":",
"result",
"=",
"[",
"]",
"op_type",
"=",
"\"index\"",
"if",
"create",
":",
"op_type",
"=",
"\"create\"",
"meta",
"=",
"self",
".",
"_meta",
"cmd",
"=",
"{",
"op_type",
":",
"{",
... | Return bulk code | [
"Return",
"bulk",
"code"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/models.py#L105-L123 | train | 29,384 |
aparo/pyes | pyes/models.py | SortedDict.insert | def insert(self, index, key, value):
"""Inserts the key, value pair before the item with the given index."""
if key in self.keyOrder:
n = self.keyOrder.index(key)
del self.keyOrder[n]
if n < index:
index -= 1
self.keyOrder.insert(index, key)
super(SortedDict, self).__setitem__(key, value) | python | def insert(self, index, key, value):
"""Inserts the key, value pair before the item with the given index."""
if key in self.keyOrder:
n = self.keyOrder.index(key)
del self.keyOrder[n]
if n < index:
index -= 1
self.keyOrder.insert(index, key)
super(SortedDict, self).__setitem__(key, value) | [
"def",
"insert",
"(",
"self",
",",
"index",
",",
"key",
",",
"value",
")",
":",
"if",
"key",
"in",
"self",
".",
"keyOrder",
":",
"n",
"=",
"self",
".",
"keyOrder",
".",
"index",
"(",
"key",
")",
"del",
"self",
".",
"keyOrder",
"[",
"n",
"]",
"i... | Inserts the key, value pair before the item with the given index. | [
"Inserts",
"the",
"key",
"value",
"pair",
"before",
"the",
"item",
"with",
"the",
"given",
"index",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/models.py#L335-L343 | train | 29,385 |
aparo/pyes | pyes/connection.py | connect | def connect(servers=None, framed_transport=False, timeout=None,
retry_time=60, recycle=None, round_robin=None, max_retries=3):
"""
Constructs a single ElasticSearch connection. Connects to a randomly chosen
server on the list.
If the connection fails, it will attempt to connect to each server on the
list in turn until one succeeds. If it is unable to find an active server,
it will throw a NoServerAvailable exception.
Failing servers are kept on a separate list and eventually retried, no
sooner than `retry_time` seconds after failure.
:keyword servers: [server]
List of ES servers with format: "hostname:port"
Default: [("127.0.0.1",9500)]
:keyword framed_transport: If True, use a TFramedTransport instead of a TBufferedTransport
:keyword timeout: Timeout in seconds (e.g. 0.5)
Default: None (it will stall forever)
:keyword retry_time: Minimum time in seconds until a failed server is reinstated. (e.g. 0.5)
Default: 60
:keyword recycle: Max time in seconds before an open connection is closed and returned to the pool.
Default: None (Never recycle)
:keyword max_retries: Max retry time on connection down
:keyword round_robin: *DEPRECATED*
:return ES client
"""
if servers is None:
servers = [DEFAULT_SERVER]
return ThreadLocalConnection(servers, framed_transport, timeout,
retry_time, recycle, max_retries=max_retries) | python | def connect(servers=None, framed_transport=False, timeout=None,
retry_time=60, recycle=None, round_robin=None, max_retries=3):
"""
Constructs a single ElasticSearch connection. Connects to a randomly chosen
server on the list.
If the connection fails, it will attempt to connect to each server on the
list in turn until one succeeds. If it is unable to find an active server,
it will throw a NoServerAvailable exception.
Failing servers are kept on a separate list and eventually retried, no
sooner than `retry_time` seconds after failure.
:keyword servers: [server]
List of ES servers with format: "hostname:port"
Default: [("127.0.0.1",9500)]
:keyword framed_transport: If True, use a TFramedTransport instead of a TBufferedTransport
:keyword timeout: Timeout in seconds (e.g. 0.5)
Default: None (it will stall forever)
:keyword retry_time: Minimum time in seconds until a failed server is reinstated. (e.g. 0.5)
Default: 60
:keyword recycle: Max time in seconds before an open connection is closed and returned to the pool.
Default: None (Never recycle)
:keyword max_retries: Max retry time on connection down
:keyword round_robin: *DEPRECATED*
:return ES client
"""
if servers is None:
servers = [DEFAULT_SERVER]
return ThreadLocalConnection(servers, framed_transport, timeout,
retry_time, recycle, max_retries=max_retries) | [
"def",
"connect",
"(",
"servers",
"=",
"None",
",",
"framed_transport",
"=",
"False",
",",
"timeout",
"=",
"None",
",",
"retry_time",
"=",
"60",
",",
"recycle",
"=",
"None",
",",
"round_robin",
"=",
"None",
",",
"max_retries",
"=",
"3",
")",
":",
"if",... | Constructs a single ElasticSearch connection. Connects to a randomly chosen
server on the list.
If the connection fails, it will attempt to connect to each server on the
list in turn until one succeeds. If it is unable to find an active server,
it will throw a NoServerAvailable exception.
Failing servers are kept on a separate list and eventually retried, no
sooner than `retry_time` seconds after failure.
:keyword servers: [server]
List of ES servers with format: "hostname:port"
Default: [("127.0.0.1",9500)]
:keyword framed_transport: If True, use a TFramedTransport instead of a TBufferedTransport
:keyword timeout: Timeout in seconds (e.g. 0.5)
Default: None (it will stall forever)
:keyword retry_time: Minimum time in seconds until a failed server is reinstated. (e.g. 0.5)
Default: 60
:keyword recycle: Max time in seconds before an open connection is closed and returned to the pool.
Default: None (Never recycle)
:keyword max_retries: Max retry time on connection down
:keyword round_robin: *DEPRECATED*
:return ES client | [
"Constructs",
"a",
"single",
"ElasticSearch",
"connection",
".",
"Connects",
"to",
"a",
"randomly",
"chosen",
"server",
"on",
"the",
"list",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/connection.py#L58-L96 | train | 29,386 |
aparo/pyes | pyes/connection.py | ThreadLocalConnection._ensure_connection | def _ensure_connection(self):
"""Make certain we have a valid connection and return it."""
conn = self.connect()
if conn.recycle and conn.recycle < time.time():
logger.debug('Client session expired after %is. Recycling.', self._recycle)
self.close()
conn = self.connect()
return conn | python | def _ensure_connection(self):
"""Make certain we have a valid connection and return it."""
conn = self.connect()
if conn.recycle and conn.recycle < time.time():
logger.debug('Client session expired after %is. Recycling.', self._recycle)
self.close()
conn = self.connect()
return conn | [
"def",
"_ensure_connection",
"(",
"self",
")",
":",
"conn",
"=",
"self",
".",
"connect",
"(",
")",
"if",
"conn",
".",
"recycle",
"and",
"conn",
".",
"recycle",
"<",
"time",
".",
"time",
"(",
")",
":",
"logger",
".",
"debug",
"(",
"'Client session expir... | Make certain we have a valid connection and return it. | [
"Make",
"certain",
"we",
"have",
"a",
"valid",
"connection",
"and",
"return",
"it",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/connection.py#L164-L171 | train | 29,387 |
aparo/pyes | pyes/connection.py | ThreadLocalConnection.connect | def connect(self):
"""Create new connection unless we already have one."""
if not getattr(self._local, 'conn', None):
try:
server = self._servers.get()
logger.debug('Connecting to %s', server)
self._local.conn = ClientTransport(server, self._framed_transport,
self._timeout, self._recycle)
except (Thrift.TException, socket.timeout, socket.error):
logger.warning('Connection to %s failed.', server)
self._servers.mark_dead(server)
return self.connect()
return self._local.conn | python | def connect(self):
"""Create new connection unless we already have one."""
if not getattr(self._local, 'conn', None):
try:
server = self._servers.get()
logger.debug('Connecting to %s', server)
self._local.conn = ClientTransport(server, self._framed_transport,
self._timeout, self._recycle)
except (Thrift.TException, socket.timeout, socket.error):
logger.warning('Connection to %s failed.', server)
self._servers.mark_dead(server)
return self.connect()
return self._local.conn | [
"def",
"connect",
"(",
"self",
")",
":",
"if",
"not",
"getattr",
"(",
"self",
".",
"_local",
",",
"'conn'",
",",
"None",
")",
":",
"try",
":",
"server",
"=",
"self",
".",
"_servers",
".",
"get",
"(",
")",
"logger",
".",
"debug",
"(",
"'Connecting t... | Create new connection unless we already have one. | [
"Create",
"new",
"connection",
"unless",
"we",
"already",
"have",
"one",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/connection.py#L173-L185 | train | 29,388 |
aparo/pyes | pyes/connection.py | ThreadLocalConnection.close | def close(self):
"""If a connection is open, close its transport."""
if self._local.conn:
self._local.conn.transport.close()
self._local.conn = None | python | def close(self):
"""If a connection is open, close its transport."""
if self._local.conn:
self._local.conn.transport.close()
self._local.conn = None | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_local",
".",
"conn",
":",
"self",
".",
"_local",
".",
"conn",
".",
"transport",
".",
"close",
"(",
")",
"self",
".",
"_local",
".",
"conn",
"=",
"None"
] | If a connection is open, close its transport. | [
"If",
"a",
"connection",
"is",
"open",
"close",
"its",
"transport",
"."
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/connection.py#L187-L191 | train | 29,389 |
aparo/pyes | pyes/connection_http.py | Connection.execute | def execute(self, request):
"""Execute a request and return a response"""
url = request.uri
if request.parameters:
url += '?' + urlencode(request.parameters)
if request.headers:
headers = dict(self._headers, **request.headers)
else:
headers = self._headers
retry = 0
server = getattr(self._local, "server", None)
while True:
if not server:
self._local.server = server = self._get_server()
try:
parse_result = urlparse(server)
conn = get_pool().connection_from_host(parse_result.hostname,
parse_result.port,
parse_result.scheme)
kwargs = dict(
method=Method._VALUES_TO_NAMES[request.method],
url=parse_result.path + url,
body=request.body,
headers=headers,
timeout=self._timeout,
)
response = conn.urlopen(**kwargs)
return RestResponse(status=response.status,
body=response.data,
headers=response.headers)
except (IOError, urllib3.exceptions.HTTPError) as ex:
self._drop_server(server)
self._local.server = server = None
if retry >= self._max_retries:
logger.error("Client error: bailing out after %d failed retries",
self._max_retries, exc_info=1)
raise NoServerAvailable(ex)
logger.exception("Client error: %d retries left", self._max_retries - retry)
retry += 1 | python | def execute(self, request):
"""Execute a request and return a response"""
url = request.uri
if request.parameters:
url += '?' + urlencode(request.parameters)
if request.headers:
headers = dict(self._headers, **request.headers)
else:
headers = self._headers
retry = 0
server = getattr(self._local, "server", None)
while True:
if not server:
self._local.server = server = self._get_server()
try:
parse_result = urlparse(server)
conn = get_pool().connection_from_host(parse_result.hostname,
parse_result.port,
parse_result.scheme)
kwargs = dict(
method=Method._VALUES_TO_NAMES[request.method],
url=parse_result.path + url,
body=request.body,
headers=headers,
timeout=self._timeout,
)
response = conn.urlopen(**kwargs)
return RestResponse(status=response.status,
body=response.data,
headers=response.headers)
except (IOError, urllib3.exceptions.HTTPError) as ex:
self._drop_server(server)
self._local.server = server = None
if retry >= self._max_retries:
logger.error("Client error: bailing out after %d failed retries",
self._max_retries, exc_info=1)
raise NoServerAvailable(ex)
logger.exception("Client error: %d retries left", self._max_retries - retry)
retry += 1 | [
"def",
"execute",
"(",
"self",
",",
"request",
")",
":",
"url",
"=",
"request",
".",
"uri",
"if",
"request",
".",
"parameters",
":",
"url",
"+=",
"'?'",
"+",
"urlencode",
"(",
"request",
".",
"parameters",
")",
"if",
"request",
".",
"headers",
":",
"... | Execute a request and return a response | [
"Execute",
"a",
"request",
"and",
"return",
"a",
"response"
] | 712eb6095961755067b2b5baa262008ade6584b3 | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/connection_http.py#L86-L128 | train | 29,390 |
jfilter/split-folders | split_folders/split.py | list_dirs | def list_dirs(directory):
"""Returns all directories in a given directory
"""
return [f for f in pathlib.Path(directory).iterdir() if f.is_dir()] | python | def list_dirs(directory):
"""Returns all directories in a given directory
"""
return [f for f in pathlib.Path(directory).iterdir() if f.is_dir()] | [
"def",
"list_dirs",
"(",
"directory",
")",
":",
"return",
"[",
"f",
"for",
"f",
"in",
"pathlib",
".",
"Path",
"(",
"directory",
")",
".",
"iterdir",
"(",
")",
"if",
"f",
".",
"is_dir",
"(",
")",
"]"
] | Returns all directories in a given directory | [
"Returns",
"all",
"directories",
"in",
"a",
"given",
"directory"
] | 5047964ce86507283b769e5e826dde909e8687da | https://github.com/jfilter/split-folders/blob/5047964ce86507283b769e5e826dde909e8687da/split_folders/split.py#L41-L44 | train | 29,391 |
jfilter/split-folders | split_folders/split.py | list_files | def list_files(directory):
"""Returns all files in a given directory
"""
return [f for f in pathlib.Path(directory).iterdir() if f.is_file() and not f.name.startswith('.')] | python | def list_files(directory):
"""Returns all files in a given directory
"""
return [f for f in pathlib.Path(directory).iterdir() if f.is_file() and not f.name.startswith('.')] | [
"def",
"list_files",
"(",
"directory",
")",
":",
"return",
"[",
"f",
"for",
"f",
"in",
"pathlib",
".",
"Path",
"(",
"directory",
")",
".",
"iterdir",
"(",
")",
"if",
"f",
".",
"is_file",
"(",
")",
"and",
"not",
"f",
".",
"name",
".",
"startswith",
... | Returns all files in a given directory | [
"Returns",
"all",
"files",
"in",
"a",
"given",
"directory"
] | 5047964ce86507283b769e5e826dde909e8687da | https://github.com/jfilter/split-folders/blob/5047964ce86507283b769e5e826dde909e8687da/split_folders/split.py#L47-L50 | train | 29,392 |
jfilter/split-folders | split_folders/split.py | setup_files | def setup_files(class_dir, seed):
"""Returns shuffled files
"""
# make sure its reproducible
random.seed(seed)
files = list_files(class_dir)
files.sort()
random.shuffle(files)
return files | python | def setup_files(class_dir, seed):
"""Returns shuffled files
"""
# make sure its reproducible
random.seed(seed)
files = list_files(class_dir)
files.sort()
random.shuffle(files)
return files | [
"def",
"setup_files",
"(",
"class_dir",
",",
"seed",
")",
":",
"# make sure its reproducible",
"random",
".",
"seed",
"(",
"seed",
")",
"files",
"=",
"list_files",
"(",
"class_dir",
")",
"files",
".",
"sort",
"(",
")",
"random",
".",
"shuffle",
"(",
"files... | Returns shuffled files | [
"Returns",
"shuffled",
"files"
] | 5047964ce86507283b769e5e826dde909e8687da | https://github.com/jfilter/split-folders/blob/5047964ce86507283b769e5e826dde909e8687da/split_folders/split.py#L89-L99 | train | 29,393 |
jfilter/split-folders | split_folders/split.py | split_files | def split_files(files, split_train, split_val, use_test):
"""Splits the files along the provided indices
"""
files_train = files[:split_train]
files_val = files[split_train:split_val] if use_test else files[split_train:]
li = [(files_train, 'train'), (files_val, 'val')]
# optional test folder
if use_test:
files_test = files[split_val:]
li.append((files_test, 'test'))
return li | python | def split_files(files, split_train, split_val, use_test):
"""Splits the files along the provided indices
"""
files_train = files[:split_train]
files_val = files[split_train:split_val] if use_test else files[split_train:]
li = [(files_train, 'train'), (files_val, 'val')]
# optional test folder
if use_test:
files_test = files[split_val:]
li.append((files_test, 'test'))
return li | [
"def",
"split_files",
"(",
"files",
",",
"split_train",
",",
"split_val",
",",
"use_test",
")",
":",
"files_train",
"=",
"files",
"[",
":",
"split_train",
"]",
"files_val",
"=",
"files",
"[",
"split_train",
":",
"split_val",
"]",
"if",
"use_test",
"else",
... | Splits the files along the provided indices | [
"Splits",
"the",
"files",
"along",
"the",
"provided",
"indices"
] | 5047964ce86507283b769e5e826dde909e8687da | https://github.com/jfilter/split-folders/blob/5047964ce86507283b769e5e826dde909e8687da/split_folders/split.py#L129-L141 | train | 29,394 |
jfilter/split-folders | split_folders/split.py | copy_files | def copy_files(files_type, class_dir, output):
"""Copies the files from the input folder to the output folder
"""
# get the last part within the file
class_name = path.split(class_dir)[1]
for (files, folder_type) in files_type:
full_path = path.join(output, folder_type, class_name)
pathlib.Path(full_path).mkdir(
parents=True, exist_ok=True)
for f in files:
shutil.copy2(f, full_path) | python | def copy_files(files_type, class_dir, output):
"""Copies the files from the input folder to the output folder
"""
# get the last part within the file
class_name = path.split(class_dir)[1]
for (files, folder_type) in files_type:
full_path = path.join(output, folder_type, class_name)
pathlib.Path(full_path).mkdir(
parents=True, exist_ok=True)
for f in files:
shutil.copy2(f, full_path) | [
"def",
"copy_files",
"(",
"files_type",
",",
"class_dir",
",",
"output",
")",
":",
"# get the last part within the file",
"class_name",
"=",
"path",
".",
"split",
"(",
"class_dir",
")",
"[",
"1",
"]",
"for",
"(",
"files",
",",
"folder_type",
")",
"in",
"file... | Copies the files from the input folder to the output folder | [
"Copies",
"the",
"files",
"from",
"the",
"input",
"folder",
"to",
"the",
"output",
"folder"
] | 5047964ce86507283b769e5e826dde909e8687da | https://github.com/jfilter/split-folders/blob/5047964ce86507283b769e5e826dde909e8687da/split_folders/split.py#L144-L155 | train | 29,395 |
nikhilkumarsingh/gnewsclient | gnewsclient/gnewsclient.py | NewsClient.get_config | def get_config(self):
"""
function to get current configuration
"""
config = {
'location': self.location,
'language': self.language,
'topic': self.topic,
}
return config | python | def get_config(self):
"""
function to get current configuration
"""
config = {
'location': self.location,
'language': self.language,
'topic': self.topic,
}
return config | [
"def",
"get_config",
"(",
"self",
")",
":",
"config",
"=",
"{",
"'location'",
":",
"self",
".",
"location",
",",
"'language'",
":",
"self",
".",
"language",
",",
"'topic'",
":",
"self",
".",
"topic",
",",
"}",
"return",
"config"
] | function to get current configuration | [
"function",
"to",
"get",
"current",
"configuration"
] | 65422f1dee9408f1b51ae6a2ee08ae478432e1d5 | https://github.com/nikhilkumarsingh/gnewsclient/blob/65422f1dee9408f1b51ae6a2ee08ae478432e1d5/gnewsclient/gnewsclient.py#L24-L33 | train | 29,396 |
nikhilkumarsingh/gnewsclient | gnewsclient/gnewsclient.py | NewsClient.params_dict | def params_dict(self):
"""
function to get params dict for HTTP request
"""
location_code = 'US'
language_code = 'en'
if len(self.location):
location_code = locationMap[process.extractOne(self.location, self.locations)[0]]
if len(self.language):
language_code = langMap[process.extractOne(self.language, self.languages)[0]]
params = {
'hl': language_code,
'gl': location_code,
'ceid': '{}:{}'.format(location_code, language_code)
}
return params | python | def params_dict(self):
"""
function to get params dict for HTTP request
"""
location_code = 'US'
language_code = 'en'
if len(self.location):
location_code = locationMap[process.extractOne(self.location, self.locations)[0]]
if len(self.language):
language_code = langMap[process.extractOne(self.language, self.languages)[0]]
params = {
'hl': language_code,
'gl': location_code,
'ceid': '{}:{}'.format(location_code, language_code)
}
return params | [
"def",
"params_dict",
"(",
"self",
")",
":",
"location_code",
"=",
"'US'",
"language_code",
"=",
"'en'",
"if",
"len",
"(",
"self",
".",
"location",
")",
":",
"location_code",
"=",
"locationMap",
"[",
"process",
".",
"extractOne",
"(",
"self",
".",
"locatio... | function to get params dict for HTTP request | [
"function",
"to",
"get",
"params",
"dict",
"for",
"HTTP",
"request"
] | 65422f1dee9408f1b51ae6a2ee08ae478432e1d5 | https://github.com/nikhilkumarsingh/gnewsclient/blob/65422f1dee9408f1b51ae6a2ee08ae478432e1d5/gnewsclient/gnewsclient.py#L36-L51 | train | 29,397 |
nikhilkumarsingh/gnewsclient | gnewsclient/gnewsclient.py | NewsClient.get_news | def get_news(self):
"""
function to get news articles
"""
if self.topic is None or self.topic is 'Top Stories':
resp = requests.get(top_news_url, params=self.params_dict)
else:
topic_code = topicMap[process.extractOne(self.topic, self.topics)[0]]
resp = requests.get(topic_url.format(topic_code), params=self.params_dict)
return self.parse_feed(resp.content) | python | def get_news(self):
"""
function to get news articles
"""
if self.topic is None or self.topic is 'Top Stories':
resp = requests.get(top_news_url, params=self.params_dict)
else:
topic_code = topicMap[process.extractOne(self.topic, self.topics)[0]]
resp = requests.get(topic_url.format(topic_code), params=self.params_dict)
return self.parse_feed(resp.content) | [
"def",
"get_news",
"(",
"self",
")",
":",
"if",
"self",
".",
"topic",
"is",
"None",
"or",
"self",
".",
"topic",
"is",
"'Top Stories'",
":",
"resp",
"=",
"requests",
".",
"get",
"(",
"top_news_url",
",",
"params",
"=",
"self",
".",
"params_dict",
")",
... | function to get news articles | [
"function",
"to",
"get",
"news",
"articles"
] | 65422f1dee9408f1b51ae6a2ee08ae478432e1d5 | https://github.com/nikhilkumarsingh/gnewsclient/blob/65422f1dee9408f1b51ae6a2ee08ae478432e1d5/gnewsclient/gnewsclient.py#L53-L62 | train | 29,398 |
nikhilkumarsingh/gnewsclient | gnewsclient/gnewsclient.py | NewsClient.parse_feed | def parse_feed(content):
"""
utility function to parse feed
"""
feed = feedparser.parse(content)
articles = []
for entry in feed['entries']:
article = {
'title': entry['title'],
'link': entry['link']
}
try:
article['media'] = entry['media_content'][0]['url']
except KeyError:
article['media'] = None
articles.append(article)
return articles | python | def parse_feed(content):
"""
utility function to parse feed
"""
feed = feedparser.parse(content)
articles = []
for entry in feed['entries']:
article = {
'title': entry['title'],
'link': entry['link']
}
try:
article['media'] = entry['media_content'][0]['url']
except KeyError:
article['media'] = None
articles.append(article)
return articles | [
"def",
"parse_feed",
"(",
"content",
")",
":",
"feed",
"=",
"feedparser",
".",
"parse",
"(",
"content",
")",
"articles",
"=",
"[",
"]",
"for",
"entry",
"in",
"feed",
"[",
"'entries'",
"]",
":",
"article",
"=",
"{",
"'title'",
":",
"entry",
"[",
"'tit... | utility function to parse feed | [
"utility",
"function",
"to",
"parse",
"feed"
] | 65422f1dee9408f1b51ae6a2ee08ae478432e1d5 | https://github.com/nikhilkumarsingh/gnewsclient/blob/65422f1dee9408f1b51ae6a2ee08ae478432e1d5/gnewsclient/gnewsclient.py#L65-L81 | train | 29,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.