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

本文涉及的产品
Elasticsearch Serverless通用抵扣包,测试体验金 200元
简介: 带你读《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

相关实践学习
以电商场景为例搭建AI语义搜索应用
本实验旨在通过阿里云Elasticsearch结合阿里云搜索开发工作台AI模型服务,构建一个高效、精准的语义搜索系统,模拟电商场景,深入理解AI搜索技术原理并掌握其实现过程。
ElasticSearch 最新快速入门教程
本课程由千锋教育提供。全文搜索的需求非常大。而开源的解决办法Elasricsearch(Elastic)就是一个非常好的工具。目前是全文搜索引擎的首选。本系列教程由浅入深讲解了在CentOS7系统下如何搭建ElasticSearch,如何使用Kibana实现各种方式的搜索并详细分析了搜索的原理,最后讲解了在Java应用中如何集成ElasticSearch并实现搜索。  
相关文章
|
7月前
|
JSON 自然语言处理 前端开发
【01】对APP进行语言包功能开发-APP自动识别地区ip后分配对应的语言功能复杂吗?-成熟app项目语言包功能定制开发-前端以uniapp-基于vue.js后端以laravel基于php为例项目实战-优雅草卓伊凡
【01】对APP进行语言包功能开发-APP自动识别地区ip后分配对应的语言功能复杂吗?-成熟app项目语言包功能定制开发-前端以uniapp-基于vue.js后端以laravel基于php为例项目实战-优雅草卓伊凡
303 72
【01】对APP进行语言包功能开发-APP自动识别地区ip后分配对应的语言功能复杂吗?-成熟app项目语言包功能定制开发-前端以uniapp-基于vue.js后端以laravel基于php为例项目实战-优雅草卓伊凡
|
5月前
|
人工智能 监控 JavaScript
HarmonyOS5云服务技术分享--ArkTS开发Node环境
本文详细讲解了在HarmonyOS(ArkTS API 9及以上)中使用云函数的开发技巧,结合Node.js和HTTP触发器,从零开始手把手教学。内容涵盖核心能力、开发流程(配置到部署)、高阶优化及常见问题解决,并提供实际应用场景示例。助你快速掌握Serverless开发,提升效率,探索跨端协作与AI集成等未来方向。
|
8月前
|
JavaScript 前端开发 数据可视化
【01】Cocos游戏开发引擎从0开发一款游戏-cocos环境搭建以及配置-Cocos Creator软件系统下载安装-node环境-优雅草卓伊凡
【01】Cocos游戏开发引擎从0开发一款游戏-cocos环境搭建以及配置-Cocos Creator软件系统下载安装-node环境-优雅草卓伊凡
429 2
【01】Cocos游戏开发引擎从0开发一款游戏-cocos环境搭建以及配置-Cocos Creator软件系统下载安装-node环境-优雅草卓伊凡
|
9月前
|
JavaScript 前端开发 jenkins
抛弃node和vscode,如何用记事本开发出一个完整的vue前端项目
本文探讨了在不依赖Node和VSCode的情况下,仅使用记事本和浏览器开发一个完整的Vue3前端项目的方法。通过CDN引入Vue、Vue Router、Element-UI等库,直接编写HTML文件实现页面功能,展示了前端开发的本质是生成HTML。虽然日常开发离不开现代工具,但掌握这种基础方法有助于快速实现想法或应对特殊环境限制。文章还介绍了如何用Node简单部署HTML文件到服务器,提供了一种高效、轻量的开发思路。
174 10
|
10月前
|
Web App开发 JavaScript 前端开发
Node.js开发
Node.js开发
188 13
|
11月前
|
存储 JavaScript 前端开发
深入浅出Node.js后端开发
在数字化时代的浪潮中,后端开发作为连接用户与数据的桥梁,扮演着至关重要的角色。本文将以Node.js为例,深入探讨其背后的哲学思想、核心特性以及在实际项目中的应用,旨在为读者揭示Node.js如何优雅地处理高并发请求,并通过实践案例加深理解。无论你是初学者还是有一定经验的开发者,这篇文章都将为你提供新的视角和思考。
|
11月前
|
Web App开发 开发框架 JavaScript
深入浅出Node.js后端开发
在这篇文章中,我们将一起探索Node.js的奇妙世界。无论你是刚接触后端开发的新手,还是希望深化理解的老手,这篇文章都适合你。我们将从基础概念开始,逐步深入到实际应用,最后通过一个代码示例来巩固所学知识。让我们一起开启这段旅程吧!
|
11月前
|
Web App开发 开发框架 JavaScript
深入浅出Node.js后端开发
本文将带你领略Node.js的魅力,从基础概念到实践应用,一步步深入理解并掌握Node.js在后端开发中的运用。我们将通过实例学习如何搭建一个基本的Web服务,探讨Node.js的事件驱动和非阻塞I/O模型,以及如何利用其强大的生态系统进行高效的后端开发。无论你是前端开发者还是后端新手,这篇文章都会为你打开一扇通往全栈开发的大门。

相关产品

  • 检索分析服务 Elasticsearch版