我是 Elastic search 和 Node js 的新手。我已经在我的电脑上成功配置了ELK。我已经使用 kibana 中的开发工具完成了基本查询。我还调用了邮递员的搜索方法。一切正常。但是当我尝试将弹性搜索集成到nodejs应用程序中时,对弹性搜索的请求失败并且没有返回任何内容。 这是小片段
const fetchElasticData = async () => {
try {
if (client.transport.connectionPool) {
console.log("Elasticsearch client is connected.");
} else {
console.log("Elasticsearch client is not connected.");
}
const { body: response } = await client.search({
index: "mongodb-data",
body: {
query: {
match_all: {},
},
},
});
console.log("Response :" + response);
console.log(response.hits.hits);
} catch (error) {
console.error("Error searching Elasticsearch:", error);
}
};
fetchElasticData()
当我尝试运行它时,我得到的输出如下:
G:\server> npm start
> [email protected] start
> node server.js
Elasticsearch client is connected.
Response :undefined
Error searching Elasticsearch: TypeError: Cannot read properties of undefined (reading 'hits')
at fetchElasticData1 (G:\server\controllers\sms_Controller.js:237:26)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
我想知道我错过了什么。非常感谢您的帮助。预先感谢!
从您的日志中我可以看到 Elasticsearch 客户端已连接。 很好,看起来 Elasticsearch 已启动并正在运行。
响应:未定义 搜索 Elasticsearch 时出错:类型错误:无法读取未定义的属性(读取“命中”)。错误消息表明响应是未定义,因此当您尝试访问
response.hits.hits
时,它会抛出错误,可能是因为响应不是对象。
curl "http://localhost:9200"
或 curl -k "https://localhost:9200" -u elastic:password
mongodb-data
索引是否存在curl "http://localhost:9200/mongodb-data"
curl "http://localhost:9200/mongodb-data/_search"
注意:您还可以在浏览器上运行上述curl命令,如下所示。 http://localhost:9200/mongodb-data/_search
如果索引存在并且其中有数据,请检查/共享elasticsearch和node.js调试日志。