操作ElasticSearch
# ES 和关系数据库的比较
ES 概念 | 关系型数据库 |
---|---|
Index(索引)支持全文检索 | Database(数据库) |
Type(类型) | Table(表) |
Document(文档),不同文档可以有不同的字段集合 | Row(数据行) |
Field(字段) | Column(数据列) |
Mapping(映射) | Schema(模式) |
# ES API
# 查看健康状态
curl -X GET 127.0.0.1:9200/_cat/health?v
1
# 查询当前 es 集群中所有的 indices
curl -X GET 127.0.0.1:9200/_cat/indices?v
1
# 创建索引
curl -X PUT 127.0.0.1:9200/www
1
# 删除索引
curl -X DELETE 127.0.0.1:9200/www
1
# 插入记录
curl -H "ContentType:application/json" -X POST 127.0.0.1:9200/user/person -d '
{
"name": "joker",
"age": 9000,
"married": true
}'
1
2
3
4
5
6
2
3
4
5
6
也可以使用 PUT 方法,但是需要传入 id
curl -H "ContentType:application/json" -X PUT 127.0.0.1:9200/user/person/4 -d '
{
"name": "sb",
"age": 9,
"married": false
}'
1
2
3
4
5
6
2
3
4
5
6
# 检索
Elasticsearch 的检索语法比较特别,使用 GET 方法携带 JSON 格式的查询条件。
全检索:
curl -X GET 127.0.0.1:9200/user/person/_search
1
按条件检索:
curl -H "ContentType:application/json" -X PUT 127.0.0.1:9200/user/person/4 -d '
{
"query":{
"match": {"name": "sb"}
}
}'
1
2
3
4
5
6
2
3
4
5
6
ElasticSearch 默认一次最多返回 10 条结果,可以像下面的示例通过 size 字段来设置返回结果的数目。
curl -H "ContentType:application/json" -X PUT 127.0.0.1:9200/user/person/4 -d '
{
"query":{
"match": {"name": "sb"},
"size": 2
}
}'
1
2
3
4
5
6
7
2
3
4
5
6
7
# Go 操作 Elasticsearch
# elastic client
我们使用第三方库https://github.com/olivere/elastic (opens new window)来连接 ES 并进行操作。
注意下载与你的 ES 相同版本的 client,例如我们这里使用的 ES 是 7.2.1 的版本,那么我们下载的 client 也要与之对应为github.com/olivere/elastic/v7
。
使用go.mod
来管理依赖:
require (
github.com/olivere/elastic/v7 v7.0.4
)
1
2
3
2
3
简单示例:
package main
import (
"context"
"fmt"
"github.com/olivere/elastic/v7"
)
// Elasticsearch demo
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
Married bool `json:"married"`
}
func main() {
client, err := elastic.NewClient(elastic.SetURL("http://127.0.0.1:9200"))
if err != nil {
// Handle error
panic(err)
}
fmt.Println("connect to es success")
p1 := Person{Name: "rion", Age: 22, Married: false}
put1, err := client.Index().
Index("user").
BodyJson(p1).
Do(context.Background())
if err != nil {
// Handle error
panic(err)
}
fmt.Printf("Indexed user %s to index %s, type %s\n", put1.Id, put1.Index, put1.Type)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
上次更新: 2025/07/18, 11:04:43