當前位置: 首頁>>代碼示例>>Python>>正文


Python elasticsearch.Elasticsearch方法代碼示例

本文整理匯總了Python中elasticsearch.Elasticsearch方法的典型用法代碼示例。如果您正苦於以下問題:Python elasticsearch.Elasticsearch方法的具體用法?Python elasticsearch.Elasticsearch怎麽用?Python elasticsearch.Elasticsearch使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在elasticsearch的用法示例。


在下文中一共展示了elasticsearch.Elasticsearch方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: parse_args

# 需要導入模塊: import elasticsearch [as 別名]
# 或者: from elasticsearch import Elasticsearch [as 別名]
def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('--es', type=str,
                        help='Root URL to Elasticsearch, ie http://localhost:9200 (defaults to envvar ELYZER_ES_URL or localhost:9200)',
                        action=EnvDefault,
                        required=True,
                        envvar='ELYZER_ES_URL',
                        default='http://localhost:9200')
    parser.add_argument('--index', type=str, action=EnvDefault,
                        required=True, envvar='ELYZER_INDEX',
                        help='Name of the index to find the analyzer, ie tweets (defaults to envvar ELYZER_INDEX)')
    parser.add_argument('--analyzer', type=str, action=EnvDefault, required=True,
                        envvar='ELYZER_ANALYZER',
                        help='Name of the custom analyzer, ie my_text_analyzer (defaults to envvar ELYZER_ANALYZER)')
    parser.add_argument('text', type=str,
                        help='Text to analyze, ie "mary had a little lamb"')
    return vars(parser.parse_args()) 
開發者ID:o19s,項目名稱:elyzer,代碼行數:19,代碼來源:__main__.py

示例2: main

# 需要導入模塊: import elasticsearch [as 別名]
# 或者: from elasticsearch import Elasticsearch [as 別名]
def main():
    try:
        args = parse_args()
        es = Elasticsearch(args['es'])
        stepWise(es=es,
                 text=args['text'],
                 indexName=args['index'],
                 analyzer=getAnalyzer(indexName=args['index'],
                                      analyzerName=args['analyzer'],
                                      es=es))

    except KeyboardInterrupt:
        print('Interrupted')
    except AnalyzerNotFound as e:
        print(e.error)
    except TransportError as e:
        print("Unexpected Elasticsearch Transport Exception:")
        print(e.error)
        print(e.info) 
開發者ID:o19s,項目名稱:elyzer,代碼行數:21,代碼來源:__main__.py

示例3: _add_prefix

# 需要導入模塊: import elasticsearch [as 別名]
# 或者: from elasticsearch import Elasticsearch [as 別名]
def _add_prefix(self, *args, **kwargs):
        if args:
            index = args[0].strip()
        else:
            index = kwargs.get("index", "").strip()
        if index is None or index == "":
            raise NotImplementedError("Elasticsearch index not specified.")

        prefix = "%s_" % self.prefix.strip() if self.prefix and self.prefix.strip() != "" else ""
        ret = []
        for idx in index.split(","):
            ret.append("%s%s" % (prefix, idx))

        index = ",".join(ret)
        if args:
            return index
        else:
            return dict(kwargs, index=index) 
開發者ID:archesproject,項目名稱:arches,代碼行數:20,代碼來源:search.py

示例4: __init__

# 需要導入模塊: import elasticsearch [as 別名]
# 或者: from elasticsearch import Elasticsearch [as 別名]
def __init__(self, client, params=None, **kwargs):
        '''
        API for performing easy bulk operations in Elasticsearch.

        :arg client: instance of official Elasticsearch Python client.
        :arg index: Default index for items which don't provide one
        :arg doc_type: Default document type for items which don't provide one
        :arg consistency: Explicit write consistency setting for the operation
        :arg refresh: Refresh the index after performing the operation
        :arg routing: Specific routing value
        :arg replication: Explicitly set the replication type (default: sync)
        :arg timeout: Explicit operation timeout

        .. Note:: all the arguments passed at the time create a new bulk
                  operation can be overridden when
                  :meth:`BulkOperation.execute`: is called.
        '''

        self._client = client
        self._params = params
        self._actions = [] 
開發者ID:wingify,項目名稱:superelasticsearch,代碼行數:23,代碼來源:__init__.py

示例5: configure

# 需要導入模塊: import elasticsearch [as 別名]
# 或者: from elasticsearch import Elasticsearch [as 別名]
def configure(parser: ArgumentParser) -> Callable:
    parser.add_argument(
        '-b', '--brokers', dest='brokers', required=True, type=str,
        help='Kafka brokers to bootstrap from as a comma separated list of <host>:<port>')
    parser.add_argument(
       '-c', '--es-clusters', dest='es_clusters', required=True, type=str,
       help='Elasticsearch servers to bootstrap from as a comma separated list of <host>:<port>')
    parser.add_argument(
        '-t', '--topic', dest='topics', required=True, type=str, nargs='+',
        help='Kafka topic(s) to read indexing requests from. Multiple topics may be provided.')
    parser.add_argument(
        '-g', '--group-id', dest='group_id', type=str, default='TODO',
        help='Kafka consumer group to join')
    parser.add_argument(
        '--prometheus-port', dest='prometheus_port', default=9170, type=int, required=False,
        help='Port to export prometheus metrics over.')
    return main 
開發者ID:wikimedia,項目名稱:search-MjoLniR,代碼行數:19,代碼來源:kafka_bulk_daemon.py

示例6: indices_map

# 需要導入模塊: import elasticsearch [as 別名]
# 或者: from elasticsearch import Elasticsearch [as 別名]
def indices_map(clusters: List[Elasticsearch]) -> Mapping[str, Elasticsearch]:
    """Map from addressable index name to elasticsearch client that contains it

    Index names that exist on multiple clusters are treated as existing on
    no clusters. Essentially this only tracks indices that are unique to
    the cluster it lives on.
    """
    indices = cast(Dict[str, Optional[Elasticsearch]], dict())
    for elastic in clusters:
        for index_name, data in elastic.indices.get_alias().items():
            for name in [index_name] + list(data['aliases'].keys()):
                if name not in indices:
                    indices[name] = elastic
                # If an index name exists on multiple clusters we
                # pretend it doesn't exist on any of them.
                elif indices[name] != elastic:
                    indices[name] = None
    return {k: v for k, v in indices.items() if v is not None} 
開發者ID:wikimedia,項目名稱:search-MjoLniR,代碼行數:20,代碼來源:kafka_bulk_daemon.py

示例7: __init__

# 需要導入模塊: import elasticsearch [as 別名]
# 或者: from elasticsearch import Elasticsearch [as 別名]
def __init__(self, client: Elasticsearch):
        super().__init__(client)
        self.cache = CacheClient(client)
        self.store = FeatureStoreClient(client)
        self.feature = FeatureClient(client)
        self.feature_set = FeatureSetClient(client)
        self.model = ModelClient(client)


# Domain objects stored in the plugin. These offer a very simple interface for
# constructing requests and interpreting results of objects stored in the ltr
# plugin.
#
# Note that when encoding these objects to send to the plugin they are almost always
# wrapped in a single-value dict containing the type. So for example to add a feature
# to a feature store:
#
#  feature = StoredFeature('test', ['keywords'], 'mustache', {"match":{"title":"{{keywords}}"}})
#  response = ltr_client.feature.create(feature.name, {'feature': feature.to_dict()}) 
開發者ID:wikimedia,項目名稱:search-MjoLniR,代碼行數:21,代碼來源:esltr.py

示例8: __init__

# 需要導入模塊: import elasticsearch [as 別名]
# 或者: from elasticsearch import Elasticsearch [as 別名]
def __init__(self, config=None):

		if isinstance(config, dict) or isinstance(config, OrderedDict):
			self.config = config
		elif isinstance(config, str):
			try:
				self.config = json.load(open(config, "r"))
			except:
				self.config = {}

		self.username = self.config.get("username", "data_security_es_45")
		self.password = self.config.get("password", "Nb6121ca7ffe3")
		es_url = self.config.get("es_url", ['http://zsearch.alipay.com:9999'])

		if isinstance(es_url, list):
			self.es_url = es_url
		else:
			self.es_url = [es_url]

		self.es = Elasticsearch(self.es_url, http_auth=(self.username, self.password)) 
開發者ID:yyht,項目名稱:BERT,代碼行數:22,代碼來源:es_indexing.py

示例9: insert_record_to_ssdeep_index

# 需要導入模塊: import elasticsearch [as 別名]
# 或者: from elasticsearch import Elasticsearch [as 別名]
def insert_record_to_ssdeep_index(ssdeep_value, sha256):
    """
    Adds a record to the ssdeep index in elasticsearch
    :param ssdeep_value: The ssdeep hash value of the item
    :param sha256: The sha256 hash value of the item
    """
    chunksize, chunk, double_chunk = ssdeep_value.split(':')
    chunksize = int(chunksize)

    es = elasticsearch.Elasticsearch(['localhost:9200'])

    document = {'chunksize': chunksize, 'chunk': chunk, 'double_chunk': double_chunk, 'ssdeep': ssdeep_value,
                'sha256': sha256}

    es.index('ssdeep-index', 'record', document)
    es.indices.refresh('ssdeep-index') 
開發者ID:intezer,項目名稱:ssdeep-elastic,代碼行數:18,代碼來源:ssdeep_querying.py

示例10: __init__

# 需要導入模塊: import elasticsearch [as 別名]
# 或者: from elasticsearch import Elasticsearch [as 別名]
def __init__(
        self,
        host="localhost",
        port=443,
        path="",
        scheme="https",
        user=None,
        password=None,
        context=None,
        **kwargs,
    ):
        super().__init__(
            host=host,
            port=port,
            path=path,
            scheme=scheme,
            user=user,
            password=password,
            context=context,
            **kwargs,
        )
        if user and password:
            self.es = Elasticsearch(self.url, http_auth=(user, password), **self.kwargs)
        else:
            self.es = Elasticsearch(self.url, **self.kwargs) 
開發者ID:preset-io,項目名稱:elasticsearch-dbapi,代碼行數:27,代碼來源:api.py

示例11: __init__

# 需要導入模塊: import elasticsearch [as 別名]
# 或者: from elasticsearch import Elasticsearch [as 別名]
def __init__(
        self,
        host="localhost",
        port=9200,
        path="",
        scheme="http",
        user=None,
        password=None,
        context=None,
        **kwargs,
    ):
        super().__init__(
            host=host,
            port=port,
            path=path,
            scheme=scheme,
            user=user,
            password=password,
            context=context,
            **kwargs,
        )
        if user and password:
            self.es = Elasticsearch(self.url, http_auth=(user, password), **self.kwargs)
        else:
            self.es = Elasticsearch(self.url, **self.kwargs) 
開發者ID:preset-io,項目名稱:elasticsearch-dbapi,代碼行數:27,代碼來源:api.py

示例12: run

# 需要導入模塊: import elasticsearch [as 別名]
# 或者: from elasticsearch import Elasticsearch [as 別名]
def run(self):
        with self.input()['Emotion'].open('r') as fopen:
            emotions = json.load(fopen)
        es = Elasticsearch()
        for i in range(0, len(emotions), self.batch_size):
            batch = emotions[i : min(i + self.batch_size, len(emotions))]
            actions = [
                {
                    '_index': self.index,
                    '_type': 'text',
                    '_id': '%d-%s' % (i + j, self.summary),
                    '_source': batch[j],
                }
                for j in range(len(batch))
            ]
            helpers.bulk(es, actions) 
開發者ID:huseinzol05,項目名稱:Gather-Deployment,代碼行數:18,代碼來源:function.py

示例13: pull_to_elastic

# 需要導入模塊: import elasticsearch [as 別名]
# 或者: from elasticsearch import Elasticsearch [as 別名]
def pull_to_elastic(**kwargs):
    ti = kwargs['ti']
    sentiments = ti.xcom_pull(task_ids = 'push_sentiment', key = 'sentiment')
    es = Elasticsearch()
    for i in range(0, len(sentiments), batch_size):
        batch = sentiments[i : min(i + batch_size, len(sentiments))]
        actions = [
            {
                '_index': 'test_index',
                '_type': 'text',
                '_id': '%d-text' % (j + i),
                '_source': batch[j],
            }
            for j in range(len(batch))
        ]
        helpers.bulk(es, actions) 
開發者ID:huseinzol05,項目名稱:Gather-Deployment,代碼行數:18,代碼來源:sentiment_to_elastic.py

示例14: create_elasticsearch_connection

# 需要導入模塊: import elasticsearch [as 別名]
# 或者: from elasticsearch import Elasticsearch [as 別名]
def create_elasticsearch_connection(data_storage=None):

        db_conn = Elasticsearch([{'host': data_storage.get("connection_uri"), 'port': 9200}])
        return db_conn 
開發者ID:invanalabs,項目名稱:invana-bot,代碼行數:6,代碼來源:base.py

示例15: get_es_connection

# 需要導入模塊: import elasticsearch [as 別名]
# 或者: from elasticsearch import Elasticsearch [as 別名]
def get_es_connection():
    """ Try to connect to es """
    hosts = build_es_connection_hosts()
    try:
        return Elasticsearch(hosts)
    except Exception as e:
        logger.warn('Could not contact ElasticSearch with provided configuration.')
        logger.warn(e)
        sys.exit(1) 
開發者ID:insightfinder,項目名稱:InsightAgent,代碼行數:11,代碼來源:getmessages_elasticsearch2.py


注:本文中的elasticsearch.Elasticsearch方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。