一、簡介
Mac Elasticsearch是一款用於實時搜索和分析的開源搜索引擎,由Apache Lucene構建而成,可通過HTTP請求進行數據搜索、存儲及分析。該搜索引擎具有快速、穩定、可擴展性強等特點,廣泛應用於全文搜索、日誌分析、應用程序性能監測等領域。
二、部署和配置
1、安裝Java運行環境
brew cask install java
2、下載elasticsearch安裝包,並解壓
wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-7.13.1-darwin-x86_64.tar.gz
tar zxvf elasticsearch-7.13.1-darwin-x86_64.tar.gz
3、修改配置文件
cd elasticsearch-7.13.1/config
vim elasticsearch.yml
在文件中添加以下內容:
cluster.name: my-application
node.name: node-1
path.data: /path/to/data
path.logs: /path/to/logs
network.host: 0.0.0.0
http.port: 9200
4、啟動elasticsearch
cd elasticsearch-7.13.1/bin
./elasticsearch
三、索引和搜索
1、創建索引
PUT /my-index
{
"settings": {
"number_of_shards": 3,
"number_of_replicas": 2
}
}
2、批量添加數據
POST /my-index/_bulk
{ "index": { "_id": "1" }}
{ "title": "Mac Elasticsearch", "body": "This is a great search engine." }
{ "index": { "_id": "2" }}
{ "title": "Java Programming", "body": "Java is a popular programming language." }
3、搜索數據
GET /my-index/_search?q=title:elasticsearch
返回結果:
{
"took": 1,
"timed_out": false,
"_shards": {
"total": 3,
"successful": 3,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 1,
"relation": "eq"
},
"max_score": 0.18232156,
"hits": [
{
"_index": "my-index",
"_type": "_doc",
"_id": "1",
"_score": 0.18232156,
"_source": {
"title": "Mac Elasticsearch",
"body": "This is a great search engine."
}
}
]
}
}
四、聚合和過濾
1、按照年齡分組,統計每組人數
GET /people/_search
{
"size": 0,
"aggs": {
"age_groups": {
"terms": {
"field": "age"
}
}
}
}
2、按照年齡分組,統計每個分組中身高最低的人的信息
GET /people/_search
{
"size": 0,
"aggs": {
"age_groups": {
"terms": {
"field": "age"
},
"aggs": {
"shortest_person": {
"top_hits": {
"sort": [
{
"height": {
"order": "asc"
}
}
],
"size": 1
}
}
}
}
}
}
3、過濾結果,只顯示身高在170cm以上的人
GET /people/_search
{
"query": {
"bool": {
"must": [
{ "match_all": {} }
],
"filter": [
{ "range": { "height": { "gte": 170 } } }
]
}
}
}
五、常用API
1、索引API
PUT /my-index
POST /my-index/_doc/1
{
"title": "Mac Elasticsearch",
"body": "This is a great search engine."
}
GET /my-index/_doc/1
DELETE /my-index/_doc/1
2、搜索API
GET /my-index/_search?q=title:elasticsearch
GET /my-index/_search
{
"query": {
"match": {
"title": "elasticsearch"
}
}
}
3、聚合API
GET /my-index/_search
{
"size": 0,
"aggs": {
"age_groups": {
"terms": {
"field": "age"
}
}
}
}
4、更新API
POST /my-index/_doc/1/_update
{
"doc": {
"title": "New title",
"body": "This is a great search engine."
}
}
5、刪除API
DELETE /my-index
六、結論
Mac Elasticsearch是一款功能強大的搜索引擎,支持實時搜索和分析等功能,而且配置簡單、API豐富,應用範圍廣泛。開發者可以根據自己的需求,通過索引和搜索實現全文搜索、日誌分析、數據監測等功能,讓應用程序性能更加優越。
原創文章,作者:JEOH,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/147961.html