Skip to main content

Javascript Client

安装依赖

npm install @elastic/elasticsearch@6
npm install array.prototype.flatmap

连接

const { Client } = require('@elastic/elasticsearch')
const client = new Client({
node: 'https://router.nasuyun.com:9200',
auth: {
username: '用户名称',
password: '用户密码'
}
})

写入索引

创建 bulk.js

bulk.js
'use strict'

require('array.prototype.flatmap').shim()
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
node: 'https://router.nasuyun.com:9200',
auth: {
username: '用户名称',
password: '用户密码'
}
})

client.bulk({
body: [
{ index: { _index: 'test', _type: 'test', _id: 1 } },
{ title: 'foo' },
{ index: { _index: 'test', _type: 'test', _id: 2 } },
{ title: 'bar' },
{ index: { _index: 'test', _type: 'test', _id: 3 } },
{ title: 'zoo' },
]
}, function (err, resp) {
if(resp.errors) {
console.log(JSON.stringify(resp, null, '\t'));
}
});

执行 bulk.js

node bulk.js

查询索引

创建 search.js

search.js
'use strict'

require('array.prototype.flatmap').shim()
const { Client } = require('@elastic/elasticsearch')
const client = new Client({
node: 'https://router.nasuyun.com:9200',
auth: {
username: '用户名称',
password: '用户密码'
}
})

// callback API
client.search({
index: 'test',
body: {
query: {
match_all: {}
}
}
}, (err, result) => {
console.log(result.body.hits)
if (err) console.error(err)
})

执行及返回

node search.js

{
"total": 3,
"max_score": 1,
"hits": [
{
"_index": "test",
"_type": "test",
"_id": "1",
"_score": 1,
"_source": {
"title": "foo"
}
},
{
"_index": "test",
"_type": "test",
"_id": "2",
"_score": 1,
"_source": {
"title": "bar"
}
},
{
"_index": "test",
"_type": "test",
"_id": "3",
"_score": 1,
"_source": {
"title": "zoo"
}
}
]
}