ElasticSearch基本用法在之前的篇章介绍过了 这里不在过多阐述
模拟假数据
- 安装库
@faker-js/faker
模拟假数据的一个库非常好用支持中文 - 使用中文 locale: [zh_CN], 设置即可
- 生成名字,邮箱,手机号,id,年龄,性别
- 生成完成之后使用fs写入
data.json
文件
假数据
Node.js集成ElasticSearch
- fs读取刚才写入的文件
- 安装ElasticSearch的包
@elastic/elasticsearc
- 连接elastic 两种模式可以使用apiKey,也可以用账号密码的模式,这儿使用账号密码,生产使用apiKey
- 检查有没有创建过这个索引
如果重复创建会报错
- 如果没有创建过这个索引就创建,并且构建映射表 也就是字段
properties
- 批量插入数据封装一个函数
bulkInsert
- 实现插入的函数
bulkInsert
- 搜索
搜索详解
根据上面代码 + 讲解基本已经大概了解其工作原理,ElasticSearch最强大的就是他的搜索能力,可以各种组合搜索,我们分别演示一下
1.全部查询
match_all 就是全部查询 注意默认只返回10条,你可以配置size看你想要返回的条数
2.模糊查询
模糊查询会进行分词,匹配所有的关键词
使用match进行模糊查询,输入需要匹配的字段如name
后面是 value 如 隐强
他会匹配数据中所有包含 隐强
这两个字的内容 我的数据中含有 隐强
蒋强
高启强
因此返回三条
3.精确查询
如果需要支持精准查询 需要设置
name: { type: 'text', fields: { keyword: { type: 'keyword', } } },
因为text类型默认会支持分词,为了全文搜索设计,但是如果要同时支持 全文匹配 + 精准匹配 需要设置 type keyword
注意这儿就不使用match了,改成term
[字段.keyword] = [value] 查询
4.组合查询
- must 必须匹配的条件 这儿匹配了(隐强)
- filter 条件过滤 这儿匹配了年龄(20-60岁的人)
- must_not 必须不匹配 (这儿表示返回的值不能有带国字的人)
- should 可选的条件 (这儿匹配了隐强)
5.聚合查询
聚合查询在Elasticsearch中用来对数据进行统计、汇总和分析,它能够提供关于数据集的深入见解和洞察
案例 统计各个年龄出现的次数 注意使用 aggs
不再是 query
了
返回值
key
:表示聚合的字段值,这里看起来是年龄。
doc_count
:表示具有该年龄的文档数量。