ElasticSearch基本用法在之前的篇章介紹過了 這里不在過多闡述
模擬假數據
- 安裝庫
@faker-js/faker
模擬假數據的一個庫非常好用支持中文 - 使用中文 locale: [zh_CN], 設置即可
- 生成名字,郵箱,手機號,id,年齡,性別
- 生成完成之后使用fs寫入
data.json
文件
import { Faker, zh_CN, } from '@faker-js/faker'
const faker = new Faker({locale: [zh_CN],
})
const generate = (total = 100) => {let arr = []for (let i = 0; i < total; i++) {arr.push({name: faker.person.fullName(),email: faker.internet.email(),phone: faker.string.numeric({ length: 11 }),id: faker.string.uuid(),age: faker.number.int({ min: 18, max: 60 }),isMale: faker.datatype.boolean(),})}return arr
}fs.writeFileSync('./data.json', JSON.stringify(generate(), null, 2))
假數據
[{"name": "隱強","email": "k7nggq88@126.com","phone": "79533230542","id": "945e80bb-9ece-428b-925c-1ed01e26d660","age": 44,"isMale": true},......]
Node.js集成ElasticSearch
- fs讀取剛才寫入的文件
- 安裝ElasticSearch的包
@elastic/elasticsearc
- 連接elastic 兩種模式可以使用apiKey,也可以用賬號密碼的模式,這兒使用賬號密碼,生產使用apiKey
- 檢查有沒有創建過這個索引
如果重復創建會報錯
- 如果沒有創建過這個索引就創建,并且構建映射表 也就是字段
properties
- 批量插入數據封裝一個函數
bulkInsert
- 實現插入的函數
bulkInsert
- 搜索
//1.第一步
const data = fs.readFileSync('./data.json', 'utf-8')
const arr = JSON.parse(data)
//2.第二步
import { Client } from '@elastic/elasticsearch';
//3.第三步
const client = new Client({node: 'http://localhost:9200',auth: {username: 'elastic',password: '123456',},
});
//4.第四步
const exists = await client.indices.exists({ index: 'users' });
//5.第五步
if (!exists) {await client.indices.create({index: 'users',mappings: {properties: {name: { type: 'text', fields: { keyword: { type: 'keyword', } } },email: { type: 'text' },phone: { type: 'text' },id: { type: 'text' },age: { type: 'integer' },isMale: { type: 'boolean' },}}})//6.第六步await bulkInsert(arr);
}
//7.第七步
const bulkInsert = async (data) => {const operations = [];data.forEach((item) => {operations.push({index: {_index: 'users',_id: item.id},})operations.push(item)})//批量插入await client.bulk({ refresh: true, operations })
}
//8.搜索
const response = await client.search({index: 'users',query: {match_all: {},},size: 100
});
console.log(response.hits.hits);
搜索詳解
根據上面代碼 + 講解基本已經大概了解其工作原理,ElasticSearch最強大的就是他的搜索能力,可以各種組合搜索,我們分別演示一下
1.全部查詢
match_all 就是全部查詢 注意默認只返回10條,你可以配置size看你想要返回的條數
const response = await client.search({index: 'users',query: {match_all: {}, //空對象即可},size: 100 //返回100條
});
2.模糊查詢
模糊查詢會進行分詞,匹配所有的關鍵詞
使用match進行模糊查詢,輸入需要匹配的字段如name
后面是 value 如 隱強
他會匹配數據中所有包含 隱強
這兩個字的內容 我的數據中含有 隱強
蔣強
高啟強
因此返回三條
const response = await client.search({index: 'users',query: {match: {name: '隱強'},},size: 100
});
console.log(response.hits.hits);
3.精確查詢
如果需要支持精準查詢 需要設置
name: { type: 'text', fields: { keyword: { type: 'keyword', } } },
因為text類型默認會支持分詞,為了全文搜索設計,但是如果要同時支持 全文匹配 + 精準匹配 需要設置 type keyword
注意這兒就不使用match了,改成term
[字段.keyword] = [value] 查詢
const response = await client.search({index: 'users',query: {term: {'name.keyword': '隱強'}},size: 100
});
console.log(response.hits.hits);
4.組合查詢
- must 必須匹配的條件 這兒匹配了(隱強)
- filter 條件過濾 這兒匹配了年齡(20-60歲的人)
- must_not 必須不匹配 (這兒表示返回的值不能有帶國字的人)
- should 可選的條件 (這兒匹配了隱強)
const response = await client.search({index: 'users',query: {bool:{must: {match: {name: '隱強'}},filter: {range: {age: {gte: 20,lte: 60}}},must_not: {match: {name: '國'}},should: {match: {name: '隱強'}}}},size: 100
});
console.log(response.hits.hits);
5.聚合查詢
聚合查詢在Elasticsearch中用來對數據進行統計、匯總和分析,它能夠提供關于數據集的深入見解和洞察
案例 統計各個年齡出現的次數 注意使用 aggs
不再是 query
了
const response = await client.search({index: 'users',aggs: {age: {terms: {field: 'age'}}},size: 100
});
console.log(response.aggregations.age.buckets);
返回值
key
:表示聚合的字段值,這里看起來是年齡。
doc_count
:表示具有該年齡的文檔數量。
[{ key: 32, doc_count: 6 }, //表示年齡32 出現6次{ key: 23, doc_count: 4 }, //表示年齡23 出現4次{ key: 28, doc_count: 4 }, //.......{ key: 29, doc_count: 4 },{ key: 49, doc_count: 4 },{ key: 51, doc_count: 4 },{ key: 60, doc_count: 4 },{ key: 21, doc_count: 3 },{ key: 22, doc_count: 3 },{ key: 24, doc_count: 3 }
]