如何用@elastic/elasticsearch客户端获取Elastic数据库用户数据索引列表
问题:如何获取Elastic数据库中包含用户数据的索引列表?
我有一个使用@elastic/elasticsearch客户端的NodeJS应用,想要从Elastic数据库中获取索引列表(indices)。刚接触Elastic,调用当前REST接口返回了695条结果,但我仅创建了少量索引。
调用Elastic查询索引的代码如下:
const express = require('express') const app = express() const { Client } = require('@elastic/elasticsearch') const clientOpts = {}; // connect info not shown const client = new Client(clientOpts) app.get('/es/indices', async (req, res) => { let queryInfo = { index: '_all' }; client.indices.stats(queryInfo).then(result => { console.log('/es/index got =', JSON.stringify(result.body, null,2)); res.send(result.body); }).catch(ex => { console.error('/es/index failed ', ex); res.status(500).send({ error: { message: ex.message, stack: ex.stack } }); }) })
以下是结果片段及我的一个索引:
"data": { "_shards": { "total": 695, "successful": 695, "failed": 0 }, "myindex": { "uuid": "xuuoc19mTJyfvjZlyMZVxB", "primaries": { "docs": { "count": 303375, "deleted": 0 },
我查阅了Elastic 7.17版本的文档,但参数说明信息有限,例如indices.stats的参数仅列出名称,缺乏详细解释。我还尝试过Stack Overflow上的aliases API方案,但返回结果远超需求。
解决方案
1. 排除系统索引,只获取用户创建的索引
Elasticsearch默认存在大量系统索引(如.security-*、.kibana-*、.monitoring-*等),这些不是你创建的用户数据索引。你可以通过索引名称模式匹配过滤它们:
修改queryInfo的index参数,用*,-.*匹配所有非系统索引(系统索引通常以.开头):
let queryInfo = { index: '*,-.*' // *匹配所有索引,-.*排除以.开头的系统索引 };
2. 用更轻量的indices.get API获取索引列表
如果只需要索引名称,不需要统计数据,indices.get比indices.stats更高效,同样支持模式过滤:
app.get('/es/indices', async (req, res) => { try { const result = await client.indices.get({ index: '*,-.*' }); // 提取所有用户索引名称 const userIndices = Object.keys(result.body); res.send({ userIndices }); } catch (ex) { console.error('/es/index failed ', ex); res.status(500).send({ error: { message: ex.message, stack: ex.stack } }); } })
3. 进一步过滤:只保留有用户数据的索引
如果要排除空的用户索引,可以基于indices.stats返回的docs.count字段过滤:
app.get('/es/indices', async (req, res) => { try { const result = await client.indices.stats({ index: '*,-.*' }); // 筛选出文档数大于0的索引 const userDataIndices = Object.entries(result.body.indices) .filter(([_, stats]) => stats.primaries.docs.count > 0) .map(([indexName]) => indexName); res.send({ userDataIndices }); } catch (ex) { console.error('/es/index failed ', ex); res.status(500).send({ error: { message: ex.message, stack: ex.stack } }); } })
额外提示
- 如果你创建的索引有特定命名规则(比如前缀为
my-),可以直接用精准匹配,比如index: 'my-*',结果会更准确。 - Elasticsearch的索引模式支持多种匹配规则,比如通配符
*、?,也可以用逗号分隔多个模式。
内容的提问来源于stack exchange,提问作者PatS
相关产品推荐
相关产品推荐

