ElasticSearch - 文档的基本操作

2019-08-19  本文已影响0人  辻子路

注意: 以下demo皆是基于es7.x,代码的语言基于node,用的是@elastic/elasticsearch三方包。首先是引入三方包

const { Client } = require('@elastic/elasticsearch')
const client = new Client({ node: 'http://localhost:9200' })

新增

async function run() {
    // 创建文档
    await client.create({
        id: '4',
        index: 'test',
        body: {
            firstName: 'x',
            lastName: 'c',
            tags: ['码农', '愤青']
        }
    })
}
run().catch(console.log)

当然也可以不传id,这时候es会自动给这个document生成id。

查看

  // 查看文档文档
    let result = await client.get({
        id: '4',
        index: 'test'
    })
    console.log(result)

修改

修改有点复杂,分为两种:

await client.index({
        id: '1',
        index: 'test',
        type: '_update',
        body: {
            doc: {
                cc: 123     // update操作
            }
        }
    })

 await client.index({
        id: '1',
        index: 'test',
        body: {
            firstName:'x'   // index操作
        }
    })

批量读取

 // 批量读取
    let result = await client.mget({
        body: {
            docs: [
                {
                    "_index": "kibana_sample_data_logs",
                    "_id": "Lhryp2wBSmjcLNNkGPRq"
                },
                {
                    "_index": "test",
                    "_id": "1"
                }
            ]
        }
    })
    console.log(result.body.docs)

批量操作查询

header\n
body\n
header\n
body\n
 // msearch 
    let result = await client.msearch({
        index: 'kibana_sample_data_logs',
        body: [
            {},
            { "query": { "match_all": {} }, "from": 0, "size": 10 },
            { "index": "test" },
            { "query": { "match_all": {} } }
        ]
    })
    console.log(result)
上一篇 下一篇

猜你喜欢

热点阅读