如何在python-elasticsearch中获取所有索引列表

85

我如何在Python中获取索引名称的列表?以下是我的目前代码:

>>> es=e.es
>>> es
<Elasticsearch([{'host': '14555f777d8097.us-east-1.aws.found.io', 'port': 9200}])>
>>> es.indices
<elasticsearch.client.indices.IndicesClient object at 0x10de86790>
# how to get a list of all indexes in this cluster?

1
你尝试过get_aliases()方法吗?根据这个例子,你应该能够使用通配符*来获取所有索引。 - Morgan Thrapp
9个回答

101

当搜索用 python-elasticsearch 库检索 aliases 信息时,这个问题就会出现。接受的答案说要使用 get_aliases,但是该方法已被删除(自2017年起)。为了获取 aliases,你可以使用以下方法:

 es.indices.get_alias("*")

更新

最新用法应该使用关键字参数:

es.indices.get_alias(index="*")


52

要获取集群中所有索引的列表,请使用通配符。

这适用于elasticsearch-py。

# Python 2
for index in es.indices.get('*'):
  print index

# Python 3
for index in es.indices.get('*'):
  print(index)

42

使用get_alias()方法的一种方式如下:

>>> indices=es.indices.get_alias().keys()
>>> sorted(indices)
[u'avails', u'hey', u'kibana-int']

有任何想法为什么这不起作用吗? res = es.search() sorted(set(res["hits"]["hits"][k]["_index"] for k in xrange(len(res["hits"]["hits"])))) - travelingbones
看起来这个方法已经从最近的python-elasticsearch版本中删除了(2017年)。 - erewok
2
此答案不适用于 es5.x 及以上版本。 - Deep Singh Baweja
4
实际上应该使用 get_alias 而不是 get_aliases(),例如:es_client.indices.get_alias().keys() API 可能自那时起已更改。 - hamed
我个人认为indices_dict = es.indices.get_alias() 更容易即时理解。 - ciurlaro

4

你可以使用Cat API:es.cat.indices(h='索引', s='索引').split()


3
如果你愿意使用 pyelasticsearch模块 ,它支持 GET _mapping 命令,可以生成集群的模式。这将使您能够查看索引,并深入每个索引以查看doc_types及其字段等信息。以下是一个示例:
import pyelasticsearch as pyes
es = pyes.ElasticSearch(["http://hostname0:9200", "http://hostname1:9200"]) ## don't accidentally type Elasticsearch, the class from the other two modules
schema = es.get_mapping() ## python dict with the map of the cluster

仅获取索引列表,

indices_full_list = schema.keys()
just_indices = [index for index in indices_full_list if not index.startswith(".")] ## remove the objects created by marvel, e.g. ".marvel-date"

这与这个问题有关。


2

我使用curl调用统计API并获取有关索引的信息。然后,我解析返回的JSON对象以找到索引名称。

curl localhost:9200/_stats

在Python中,您可以使用requests库调用curl。我不知道如何使用Elasticsearch或Elasticsearch-DSL Python库执行此操作。

由于某些原因,*/_stats 对我来说不起作用,但是*/_mapping确实有作用。 - ximiki

2
您可以通过执行类似下面的操作来获取_mapping以获取所有索引的列表。
requests.get(full_elastic_url + "/_mapping")

1
如果你想要“别名”而不是“索引名”,这里有一个完美的解决方案:
response = es.indices.get(indexname)
alias_names = list(response[indexname]['aliases'].keys())

alias_names中,我们获取特定索引上的别名列表。

1

_cat API 似乎是正确的方法,因为 _aliases 的方式即将被 Elasticsearch 移除,因为它会暴露系统索引。

indices = es.cat.indices(h='index', s='index').split()

它对我来说起到了作用。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接