Elasticsearch Node.js

npm安装elasticsearch node客户端

npm install @elastic/elasticsearch@6

兼容性说明:
Elasticsearch Node.js

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.' } } ]
上一篇:elasticsearch 分词


下一篇:Elasticsearch实例磁盘占用率高排查及解决