npm安裝elasticsearch node用戶端
npm install @elastic/elasticsearch@6
相容性說明:

Node.js最低版本v8
該類庫支援所有5.x以上版本,但推薦使用與ES執行個體相同大版本的類庫。本例使用阿裡雲Elasticsearch6.7.0,是以安裝:@elastic/elasticsearch@6
預先在kibana建立好索引
PUT game-of-thrones
'use strict'
const {Client} = require('@elastic/elasticsearch')
const client = new Client({
node: 'http://elastic:***@es-cn-***.public.elasticsearch.aliyuncs.com:9200'
})
async function run () {
// Let's start by indexing some data
await client.index({
index: 'game-of-thrones',
type: '_doc',
body: {
character: 'Ned Stark',
quote: 'Winter is coming.'
}
})
await client.index({
index: 'game-of-thrones',
type: '_doc',
body: {
character: 'Daenerys Targaryen',
quote: 'I am the blood of the dragon.'
}
})
await client.index({
index: 'game-of-thrones',
type: '_doc',
// here we are forcing an index refresh,
// otherwise we will not get any result
// in the consequent search
refresh: true,
body: {
character: 'Tyrion Lannister',
quote: 'A mind needs books like a sword needs a whetstone.'
}
})
// Let's search!
const { body } = await client.search({
index: 'game-of-thrones',
type: '_doc',
body: {
query: {
match: {
quote: 'winter'
}
}
}
})
console.log(body.hits.hits)
}
run().catch(console.log)
在指令行運作,得到搜尋的傳回結果。
GarydeMacBook-Pro:web_design gary$ node es.js
[ { _index: 'game-of-thrones',
_type: '_doc',
_id: '8Y4q-2sBjFTorFehKRRK',
_score: 0.2876821,
_source: { character: 'Ned Stark', quote: 'Winter is coming.' } } ]