Elasticsearch:ES|QL 查询 TypeScript 类型
warning:
这篇文章距离上次修改已过186天,其中的内容可能已经有所变动。
// 引入Elasticsearch的Client
import { Client } from '@elastic/elasticsearch';
// 创建Elasticsearch客户端实例
const client = new Client({
node: 'http://localhost:9200',
});
// 定义一个函数,用于执行Elasticsearch查询并返回结果的类型
async function fetchTypes(indexName: string): Promise<string[]> {
try {
// 使用Elasticsearch的cat.types API来获取索引的类型列表
const response = await client.cat.types({
index: indexName,
format: 'json',
});
// 返回类型列表
return response.body.types;
} catch (error) {
// 错误处理
console.error('Error fetching types:', error);
return [];
}
}
// 使用示例
(async () => {
const indexName = 'kibana_sample_data_ecommerce';
const types = await fetchTypes(indexName);
console.log('Types in index %s:', indexName, types);
})();
这段代码首先引入了Elasticsearch的Client,然后创建了一个客户端实例。定义了一个异步函数fetchTypes
,它接受一个索引名称作为参数,并返回一个Promise,该Promise解析为一个字符串数组,表示索引中的类型。如果查询成功,它会返回类型列表;如果发生错误,它会记录错误并返回一个空数组。最后,代码展示了如何调用这个函数并打印出返回的类型列表。
评论已关闭