带你读《Elastic Stack 实战手册》之66:——3.5.19.2.Elasticsearch语言开发(Node.js)(下)

本文涉及的产品
检索分析服务 Elasticsearch 版,2核4GB开发者规格 1个月
简介: 带你读《Elastic Stack 实战手册》之66:——3.5.19.2.Elasticsearch语言开发(Node.js)(下)

《Elastic Stack 实战手册》——三、产品能力——3.5 进阶篇——3.5.19.Elasticsearch语言开发(Python/Nodejs/Java)——3.5.19.2.Elasticsearch语言开发(Node.js)(中) https://developer.aliyun.com/article/1226589


3. Mapping API

 

Mapping 主要作用如下:

 

l 定义索引中的字段名称

l 定义字段的类型,例如数值、字符串、布尔类型等

l 定义倒排索引的相关配置,例如是否索引、记录 position 信息等。

 下面示例是在空索引上定义了其 Mapping:


client.indices.putMapping({
  index: 'author-index',
  // 默认即为 false,因 type 在 ES 7.0 被废弃
  // 另外在 ES 8.0 中 include_type_name 也将被废弃
  include_type_name: false,
  ignore_unavailable: true,
  body: {
    properties: {
      author: { type: 'keyword' },
      article: { type: 'text' },
      age: { type: 'integer' },
      interests: { type: 'text', fielddata: true },
      createTime: { type: 'date' },
    },
  },
})
  .then(({ body }) => {
    console.log(JSON.stringify(body));
  })
  .catch(console.error);

4. Bulk API

 

Bulk API 接受索引、创建、删除和更新操作,下面以批量创建为例:

const dataset = [
  {
    author: 'Tom',
    article: 'All time is no time when it is past.',
    age: 13,
    interests: ['sports', 'painting'],
createTime: '2020-01-12',},
  {
    author: 'Mary',
    article: 'No one can call back yesterday;Yesterday will not be called again.',
    age: 15,
    interests: ['sports', 'painting', 'game', 'music'],
    createTime: '2021-03-04',
  },
  {
    author: 'David',
    article: 'Punctuality is the soul of business.',
    age: 9,
    interests: ['game'],
    createTime: '2020-09-22',
  },
];
const bulkBody = dataset.flatMap((doc, index) => [
  { index: { _index: 'author-index', _type: '_doc', _id: index + 1 } },
  doc,
]);
client
  .bulk({
    index: 'author-index',
    type: '_doc',
    // 立即刷新数据提高搜索的实时性,缺点是消耗资源较高
    refresh: true,
    body: bulkBody,
  })
  .then(({ body }) => {
    console.log(JSON.stringify(body));
  })
  .catch(console.error);

5. Update API

 

使用指定脚本更新文档,下面代码展示了对 id 为 0 的文档的 age 字段执行 +1 操作:

client
  .update({
    index: 'author-index',
    id: 0,
    refresh: true,
    body: {
      script: {
        source: 'ctx._source.age++',
        lang: 'painless',
      },
    },
  })
  .then(({ body }) => {
    console.log(JSON.stringify(body));
  })
  \ .catch(console.error);

6. UpdateByQuery API

 

下面代码展示了对 author 为 Mary 执行更新操作:

client
  .updateByQuery({
    index: 'author-index',
    refresh: true,
    body: {
      script: {
        source: 'ctx._source.age++',
           lang: 'painless',
      },
      query: {
        match: {
          author: 'Mary',
        },
      },
    },
  })
  .then(({ body }) => {
    console.log(JSON.stringify(body));
  })
  .catch(console.error);

7. Search API

 

查询 article field 中带有 time 关键字的结果:

client
  .search({
    index: 'author-index',
    body: {
      query: {
        match: {
          article: 'time',
        },
      },
    },
  })
  .then(({ body }) => {
    console.log(JSON.stringify(body));
  }) .catch(console.error);
  // search result
{
    "took":1,
    "timed_out":false,
    "_shards":{
        "total":1,
        "successful":1,
        "skipped":0,
        "failed":0
    },
    "hits":{
        "total":{
            "value":2,
            "relation":"eq"
        },
        "max_score":0.9763484,
        "hits":[
            {
                "_index":"author-index",
                "_type":"_doc",
                "_id":"1",
                "_score":0.9763484,
                "_source":{
                    "author":"Tom",
                    "article":"All time is no time when it is past.",
                    "age":13,
                    "interests":[
                        "sports",
                        "painting"
                    ],
                    "createTime":"2020-01-12"
                }
            },
             {
                "_index":"author-index",
                "_type":"_doc",
                "_id":"0",
                "_score":0.94855565,
                "_source":{
                    "author":"John",
                    "article":"Everything has its time and that time must be watched.",
                      "age":11,
                    "interests":[
                        "sports",
                        "music"
                    ],
                    "createTime":"2021-11-15"
                }
            }
        ]
    }
}


8. Aggregate API

 

下面代码展示了聚合 interests 信息的操作:


client
  .search({
    index: 'author-index',
    body: {
      aggs: {
        all_interests: {
          terms: { field: 'interests' },
        },
            },
    },
  })
  .then(({ body }) => {
    console.log(JSON.stringify(body));
  })
  .catch(console.error);
  // search result
{
    "took":3,
    "timed_out":false,
    "_shards":{
        "total":1,
        "successful":1,
        "skipped":0,
        "failed":0
    },
    "hits":{
        "total":{
            "value":4,
                 "relation":"eq"
        },
        "max_score":1,
        "hits":[
            {
                "_index":"author-index",
                "_type":"_doc",
                "_id":"1",
                "_score":1,
                "_source":{
                    "author":"Tom",
                    "article":"All time is no time when it is past.",
                     "age":13,
                    "interests":[
                        "sports",
                        "painting"
                    ],
                    "createTime":"2020-01-12"
                }
            },
            {
                "_index":"author-index",
                "_type":"_doc",
                "_id":"3",
                "_score":1,
                "_source":{
                    "author":"David",
                    "article":"Punctuality is the soul of business.",
                    "age":9,
                    "interests":[
                        "game"
                    ],
                    "createTime":"2020-09-22"
                }
            },
            {
                "_index":"author-index",
                "_type":"_doc",
                "_id":"0",
                "_score":1,
                "_source":{
                    "author":"John",
                    "article":"Everything has its time and that time must be watched.",
                    "age":11,
                                  "interests":[
                                         "sports",
                        "music"
                    ],
                    "createTime":"2021-11-15"
                }
            },
            {
                "_index":"author-index",
                "_type":"_doc",
                "_id":"2",
                "_score":1,
                "_source":{
                    "createTime":"2021-03-04",
                    "author":"Mary",
                    "interests":[
                        "sports",
                        "painting",
                        "game",
                        "music"
                    ],
                    "article":"No one can call back yesterday;Yesterday will not be called again.",
                    "age":16
                }
            }
        ]
    },
    "aggregations":{
        "all_interests":{
            "doc_count_error_upper_bound":0,
            "sum_other_doc_count":0,
            "buckets":[
                {
                      "key":"sports",
                    "doc_count":3
                },
                {
                    "key":"game",
                    "doc_count":2
                },
                {
                    "key":"music",
                         "doc_count":2
                },
                {
                    "key":"painting",
                    "doc_count":2
                }
            ]
        }
    }
}

9. Delete Index API

 

下面展示了删除索引:

client.indices
  .delete({
    index: 'author-index',
  })
  .then(({ body }) => {
    console.log(JSON.stringify(body));
  })
  .catch(console.error);

五、github 代码

 

完整的 API 示例代码请参考:https://github.com/jkhhuse/elasticsearch-nodejs

 

参考资料

 

l https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html

 

创作人简介:

姜康,一名会点 vue、Angular、React、Node.js、Java、ELK 的伪全栈前端工程师,目前正在掌握数据开发技术栈的途中。

博客:https://www.zhihu.com/people/ant_elephant/posts

相关实践学习
使用阿里云Elasticsearch体验信息检索加速
通过创建登录阿里云Elasticsearch集群,使用DataWorks将MySQL数据同步至Elasticsearch,体验多条件检索效果,简单展示数据同步和信息检索加速的过程和操作。
ElasticSearch 入门精讲
ElasticSearch是一个开源的、基于Lucene的、分布式、高扩展、高实时的搜索与数据分析引擎。根据DB-Engines的排名显示,Elasticsearch是最受欢迎的企业搜索引擎,其次是Apache Solr(也是基于Lucene)。 ElasticSearch的实现原理主要分为以下几个步骤: 用户将数据提交到Elastic Search 数据库中 通过分词控制器去将对应的语句分词,将其权重和分词结果一并存入数据 当用户搜索数据时候,再根据权重将结果排名、打分 将返回结果呈现给用户 Elasticsearch可以用于搜索各种文档。它提供可扩展的搜索,具有接近实时的搜索,并支持多租户。
相关文章
|
7天前
|
Web App开发 缓存 JavaScript
深入浅出Node.js后端开发
【9月更文挑战第26天】本文将引导你了解Node.js的基本原理,并通过实际案例展示如何在后端开发中应用它。我们将从Node.js的核心概念讲起,逐步深入到构建一个完整的后端服务,最后探讨如何优化你的Node.js应用。准备好让你的开发技能更上一层楼了吗?让我们一起潜入Node.js的世界!
|
10天前
|
JavaScript 前端开发 API
深入浅出Node.js后端开发
【9月更文挑战第23天】在这篇文章中,我们将探索Node.js的世界,了解它如何改变后端开发的面貌。通过实际案例和代码示例,我们不仅学习Node.js的核心概念,还会深入探讨它的高级特性,如异步编程、事件驱动模型以及微服务架构的应用。无论你是初学者还是有经验的开发者,这篇文章都将为你提供新的视角和实用技能,帮助你构建更高效、可扩展的后端系统。
43 19
|
8天前
|
JavaScript 开发者
深入理解Node.js事件循环及其在后端开发中的应用
【8月更文挑战第57天】本文将带你走进Node.js的事件循环机制,通过浅显易懂的语言和实例代码,揭示其背后的工作原理。我们将一起探索如何高效利用事件循环进行异步编程,提升后端应用的性能和响应速度。无论你是Node.js新手还是有一定经验的开发者,这篇文章都能给你带来新的启发和思考。
|
6天前
|
Web App开发 JavaScript 前端开发
探索现代JavaScript开发:ECMAScript提案的未来
JavaScript是最受欢迎的编程语言之一,其发展迅速。ECMAScript(JS的标准化版本)的提案和更新为其带来了诸多新特性和改进。本文将介绍值得关注的ECMAScript提案,如可选链、空值合并运算符、逻辑赋值运算符、类字段和顶级Await,并展示如何利用这些新特性提升开发效率和代码质量。通过关注TC39提案流程、使用Babel和TypeScript等工具,开发者可以提前体验并利用这些新特性。随着JavaScript的不断进步,未来将有更多令人期待的功能加入。
|
8天前
|
Web App开发 JavaScript 前端开发
深入浅出Node.js后端开发
【9月更文挑战第25天】本文将带你了解Node.js的基本概念和核心优势,同时提供一些实际的代码示例来加深理解。无论你是初学者还是有一定经验的开发者,都能通过本文获得有价值的信息和技巧。让我们一起探索Node.js的世界吧!
|
18天前
|
Web App开发 存储 JavaScript
深入浅出Node.js后端开发
【9月更文挑战第15天】在数字化浪潮中,Node.js作为一颗耀眼的星辰,为后端开发领域注入了活力与创新。本文将带你领略Node.js的魅力所在,探索其架构设计、性能优化及实战应用,让你在轻松愉快的氛围中掌握Node.js后端开发的精髓。
|
22天前
|
Web App开发 JavaScript 前端开发
深入浅出Node.js后端开发
【9月更文挑战第11天】本文将带你走进Node.js的世界,了解其背后的运行机制和实际应用。我们将从基础概念出发,逐步深入到实战应用,最后通过代码示例巩固学习成果。无论你是初学者还是有一定经验的开发者,这篇文章都将为你提供新的视角和思考。
|
20天前
|
JavaScript 前端开发 API
深入浅出Node.js后端开发
【9月更文挑战第13天】本文将带你进入Node.js的世界,从基础概念到实际案例,深入浅出地探讨如何利用Node.js进行后端开发。通过本文的学习,你将了解Node.js的工作原理、核心模块、以及如何构建一个简单的Web应用。无论你是初学者还是有一定经验的开发者,这篇文章都将为你提供有价值的见解和技巧。
|
22天前
|
Web App开发 JavaScript NoSQL
深入浅出Node.js后端开发
在数字化时代的浪潮中,后端开发作为技术支柱之一,承载着数据处理和业务逻辑实现的重要任务。本文将通过浅显易懂的方式,带你走进Node.js的世界,从基础概念到实战应用,逐步揭开后端开发的神秘面纱。无论你是编程新手还是希望扩展技术栈的开发者,这篇文章都将为你提供有价值的指导和启示。让我们一起探索如何在不断变化的技术环境中,保持初心,寻找属于自己的方向,并成为希望在世界上看到的改变。
32 1
|
22天前
|
缓存 JavaScript 前端开发
深入浅出Node.js后端开发
【9月更文挑战第11天】本文将带你进入Node.js的世界,探索其背后的哲学、核心概念以及如何利用它来构建高效、可扩展的后端服务。无论你是前端开发者寻求全栈技能,还是后端开发者希望拓宽技术栈,这篇文章都将为你提供价值。我们将从基础讲起,逐步深入到实战应用,让你对Node.js有一个全面而深刻的理解。
31 2

热门文章

最新文章

相关产品

  • 检索分析服务 Elasticsearch版
  • 下一篇
    无影云桌面