ElasticSearch
安装
npm install @elastic/elasticsearch
使用
const { Client } = require('@elastic/elasticsearch');
const client = new Client({ node: 'http://localhost:9200' });
index 表示索引;size 表示每页的数据条数,默认 10;from 表示跳过开始的结果数,默认 0,比如第一页返回 10 条数据,第二页就从第 11 条开始返回,即 from 为 10
client
.search({
index: 'lgbzdzk',
size: 10,
from: 0,
body: {
track_total_hits: true, // 默认值为10000,设为true后可精确计数
query: {
match: {
name: '高级前端'
}
},
aggs: {
house_count: {
cardinality: {
field: 'RZF_XZDXXDZ.keyword'
}
}
}
}
})
.then(res => {
let total = res.body.hits.total;
let arrPoint = res.body.hits.hits;
console.log(arrPoint);
console.log(total);
console.log(res.body.aggregations); // 房屋去重计数
})
.catch(e => {
console.log(e);
});
搜索
通用匹配
{
"query": {
"match": {
"name": "高级前端"
}
}
}
自动分词,会将含有“高级”和“前端”字样的数据都匹配出来
短语匹配
短语匹配不存在分词的情况,类似于精确匹配
{
"query": {
"match_phrase": {
"BIP_XM": "张三丰"
}
}
}
多字段匹配
多个字段内只要含有关键词都会被匹配出来
{
"query": {
"multi_match": {
"query": "北京市朝阳区",
"fields": ["RZF_XZDXXDZ", "RZF_DZ"]
}
}
}
布尔查询
must 关键词,表示所有条件必须满足
还有 should 表示或的关系、must_not 表示一定不满足
{
"query": {
"bool": {
"must": [
{
"match": {
"BIP_XM": "张三"
}
},
{
"term": {
"BIP_SFZHM": "412824196808303929"
}
}
]
}
}
}
去重计数
统计某个字段上出现的不同值的个数
"house_count"为自定义字段,聚合字段需要 keyword 类型
{
"query": {},
"aggs": {
"house_count": {
"cardinality": {
"field": "RZF_XZDXXDZ.keyword"
}
}
}
}