美文网首页
Nodejs中@elastic/elasticsearch的使用

Nodejs中@elastic/elasticsearch的使用

作者: 阿拉斌 | 来源:发表于2019-08-08 21:37 被阅读0次

    GitHub的地址:
    https://github.com/elastic/elasticsearch-js

    小问题

    1. elasticsearch查询结果只显示一万

    我们在进行查询的时候,应该选择scroll的方式进行查询,我还看到了一个,用排序搜索的,我用的就是排序的搜索

    首先,使用elasticsearch-head将对应的索引进行关闭,之后对索引进行设置。我们对目标索引发送put请求,请求的地址示例:http://localhost:9200/aaa/_settings,参数:{ "index" : { "max_result_window" : 500000}},设置完成后,重新打开就可以了,这样结果字段就会显示完整的了

    快速开始

    首先,初始化它

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

    您可以通过回调函数,或者Promise来使用

    // promise API
    const result = await client.search({
      index: 'my-index',
      body: { foo: 'bar' }
    })
    
    // callback API
    client.search({
      index: 'my-index',
      body: { foo: 'bar' }
    }, (err, result) => {
      if (err) console.log(err)
    })
    

    每个** API调用返回的**值形成如下形式:

    {
      body: object | boolean
      statusCode: number
      headers: object
      warnings: [string]
      meta: object
    }
    

    让我们看一个完整的例子!

    'use strict'
    
    const { Client } = require('@elastic/elasticsearch')
    const client = new Client({ node: 'http://localhost:9200' })
    
    async function run () {
      // 让我们从索引一些数据开始
      await client.index({
        // 索引的名称
        index: 'game-of-thrones',
        // 如果您使用的是Elasticsearch≤6,取消对这一行的注释
        // type: '_doc',
        body: {
          character: 'Ned Stark',
          quote: 'Winter is coming.'
        }
      })
    
      await client.index({
        index: 'game-of-thrones',
        // 如果您使用的是Elasticsearch≤6,取消对这一行的注释
        // type: '_doc',
        body: {
          character: 'Daenerys Targaryen',
          quote: 'I am the blood of the dragon.'
        }
      })
    
      await client.index({
        index: 'game-of-thrones',
        // 如果您使用的是Elasticsearch≤6,取消对这一行的注释
        // type: '_doc',
        body: {
          character: 'Tyrion Lannister',
          quote: 'A mind needs books like a sword needs a whetstone.'
        }
      })
    
      // 这里我们强制执行索引刷新,否则在随后的搜索中不会得到任何结果
      await client.indices.refresh({ index: 'game-of-thrones' })
    
      // 开始搜索
      const { body } = await client.search({
        index: 'game-of-thrones',
        // 如果您使用的是Elasticsearch≤6,取消对这一行的注释
        // type: '_doc',
        body: {
          query: {
            match: { quote: 'winter' }
          }
        }
      })
    
      console.log(body.hits.hits)
    }
    
    run().catch(console.log)
    

    在TS中使用

    定义一个接口

    export interface IEsResult<T> {
        body: {
            /**
             * 耗时,毫秒
             */
            took: number,
            timed_out: boolean,
            /**
             * 结果数据
             */
            hits: {
                /**
                 * 结果集合
                 */
                hits: T[],
                /**
                 * 计数
                 */
                total: {
                    /**
                     * 关系
                     */
                    relation: "eq",
                    /**
                     * 一共多少数据
                     */
                    value: number
                }
            },
        },
        /**
         * 单页大小
         */
        size?: number;
        /**
         * 总页数
         */
        pages?: number;
    }
    

    获取数据

        /**
         * 获取ES查询出来的数据,这里使用的是对name进行类似于sql中的like "%aaa%" 的查询方式,其他的查询方式,后面再补上
         * @param index 索引
         * @param keyword 关键词
         * @param pagenum 页码
         * @param size 单页大小
         */
        async getEsData(index: string, keyword: any, pagenum: number, size: number) {
            // 获取数据
            const result: IEsResult<any> = await this.searcClient.search({
                index,
                body: {
                    track_total_hits: true,
                    query: {
                        bool: {
                            must: [{
                                "query_string": {
                                    "default_field": "name",
                                    "query": "*" + name+ "*"
                                }
                            }],
                            must_not: [],
                            should: []
                        }
                    },
                    search_after: [(pagenum - 1) * size],
                    size: size,
                    sort: [
                        {"_id": "asc"}
                    ]
                }
            });
            result.size = size;
            result.pages = Math.ceil(result.body.hits.total.value / size);
            return result;
        }
    

    新增数据

    在搜索引擎里面不叫新增数据,叫做创建索引,使用的是index的方法

      await client.index({
        index: 'game-of-thrones',
        // type: '_doc', // uncomment this line if you are using Elasticsearch ≤ 6
        body: {
          character: 'Daenerys Targaryen',
          quote: 'I am the blood of the dragon.'
        }
      })
    

    删除操作

    client.delete({
      id: string,
      index: string,
      type: string,
      wait_for_active_shards: string,
      refresh: 'true' | 'false' | 'wait_for',
      routing: string,
      timeout: string,
      if_seq_no: number,
      if_primary_term: number,
      version: number,
      version_type: 'internal' | 'external' | 'external_gte' | 'force'
    })
    

    更新操作

    在经过查询和删除的操作后,基本上已经可以知道,ES在node里面基本使用,主要是对body对象的属性进行扩展,比如我要更新单个文档:

      const result: any = await this.searcClient.update({
            id,
            index,
            body: {
                doc: params,
                // script: "ctx._source.city = \'北京\'"
            }
        });
    

    在API中,还有一个是根据条件进行批量更新,它是这样的:

        // 条件更新是不需要id的
        const result: any = await this.searcClient.updateByQuery({
            index,
            body: {
                query: {
                    bool: {
                        must: [{
                            "query_string": {
                                "default_field": "jyfw.keyword",
                                "query": "*" + keyword + "*"
                            }
                        }],
                    }
                },
                script: {
                    // 执行的脚本语言
                    lang: "painless",
                    inline: "ctx._source.city = \'北京\'"
                }
            }
        });
    

    相关文章

      网友评论

          本文标题:Nodejs中@elastic/elasticsearch的使用

          本文链接:https://www.haomeiwen.com/subject/tugfjctx.html