Skip to content

操作ElasticSearch

ES 和关系数据库的比较

ES 概念关系型数据库
Index(索引)支持全文检索Database(数据库)
Type(类型)Table(表)
Document(文档),不同文档可以有不同的字段集合Row(数据行)
Field(字段)Column(数据列)
Mapping(映射)Schema(模式)

ES API

查看健康状态

plain
curl -X GET 127.0.0.1:9200/_cat/health?v

查询当前 es 集群中所有的 indices

plain
curl -X GET 127.0.0.1:9200/_cat/indices?v

创建索引

plain
curl -X PUT 127.0.0.1:9200/www

删除索引

plain
curl -X DELETE 127.0.0.1:9200/www

插入记录

plain
curl -H "ContentType:application/json" -X POST 127.0.0.1:9200/user/person -d '
{
	"name": "joker",
	"age": 9000,
	"married": true
}'

也可以使用 PUT 方法,但是需要传入 id

plain
curl -H "ContentType:application/json" -X PUT 127.0.0.1:9200/user/person/4 -d '
{
	"name": "sb",
	"age": 9,
	"married": false
}'

检索

Elasticsearch 的检索语法比较特别,使用 GET 方法携带 JSON 格式的查询条件。

全检索:

plain
curl -X GET 127.0.0.1:9200/user/person/_search

按条件检索:

plain
curl -H "ContentType:application/json" -X PUT 127.0.0.1:9200/user/person/4 -d '
{
	"query":{
		"match": {"name": "sb"}
	}
}'

ElasticSearch 默认一次最多返回 10 条结果,可以像下面的示例通过 size 字段来设置返回结果的数目。

plain
curl -H "ContentType:application/json" -X PUT 127.0.0.1:9200/user/person/4 -d '
{
	"query":{
		"match": {"name": "sb"},
		"size": 2
	}
}'

Go 操作 Elasticsearch

elastic client

我们使用第三方库https://github.com/olivere/elastic来连接 ES 并进行操作。

注意下载与你的 ES 相同版本的 client,例如我们这里使用的 ES 是 7.2.1 的版本,那么我们下载的 client 也要与之对应为github.com/olivere/elastic/v7

使用go.mod来管理依赖:

go
require (
    github.com/olivere/elastic/v7 v7.0.4
)

简单示例:

go
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)
}
最近更新