go olivereパッケージ操作elasticsearchを呼び出す一般的な基本操作

51150 ワード

go olivereパッケージ操作elasticsearchを呼び出す一般的な基本操作
次のくどくどした公式文書を見たくありません:ここをクリックします
完全なサンプルコード:
package main

import (
	"context"
	"fmt"
	"github.com/olivere/elastic/v7"
	"time"
)

type User struct {
	Name    string    `json:"name"`
	Age     int       `json:"age"`
	Married bool      `json:"married"`
	Sex string        `json:"sex"`
	Created time.Time `json:"created, omitempty"`
	Tags     []string              `json:"tags,omitempty"`
	Location string                `json:"location,omitempty"`
	Suggest  *elastic.SuggestField `json:"suggest_field,omitempty"`
}

//       ,mapping    index    
const mapping = `
{
	"settings":{
		"number_of_shards": 1,
		"number_of_replicas": 0
	},
	"mappings":{
			"properties":{
				"name":{
					"type":"text"
				},
				"age":{
					"type":"long"
				},
				"married":{
				"type":"boolean"
				},
				"created":{
					"type":"date"
				},
				"tags":{
					"type":"keyword"
				},
				"location":{
					"type":"geo_point"
				},
				"suggest_field":{
					"type":"completion"
				}
		}
	}
}`
const mapping1 = `
{
  "properties": {
    "sex": {
      "type": "text"
    }
  }
}
}`
var ctx = context.Background()
var esUrl string = "http://192.168.1.109:9200"

func main() {

	//     
	client, err := elastic.NewClient(elastic.SetURL(esUrl), elastic.SetSniff(false))
	if err != nil {
		// Handle error
		panic(err)
	}
	// Ping the Elasticsearch server to get e.g. the version number
	// ping    ,       es  ,    es   version 7.6.1
	info, code, err := client.Ping(esUrl).Do(ctx)
	if err != nil {
		// Handle error
		panic(err)
	}
	fmt.Printf("Elasticsearch returned with code>: %d and version %s
"
, code, info.Version.Number) // API esVersion, err := client.ElasticsearchVersion(esUrl) if err != nil { panic(err) } fmt.Printf("es %s
"
, esVersion) // index , es index //exists, err := client.IndexExists("user").Do(ctx) //if err != nil { // panic(err) //} //if !exists { // // , // createIndex, err := client.CreateIndex("user").BodyString(mapping1).Do(ctx) // if err != nil { // // Handle error // panic(err) // } // if !createIndex.Acknowledged { // // Not acknowledged , // } //// //} //// // //_, err = client.PutMapping().Index("user").BodyString(mapping1).Do(ctx) //if err != nil { // fmt.Println(err) // panic(err) //} // 1 //user1 := User{Name:"bob",Sex:"male",Married:false,Age:23} //put1,err :=client.Index().Index("user").BodyJson(user1).Id("1").Do(ctx) //if err != nil{ // panic(err) //} //fmt.Printf("Indexed user %s to index %s, type %s
", put1.Id, put1.Index, put1.Type) //Indexed user 1 to index user, type _doc
//// 2 //user2 := `{"name":"mike","sex":"male","married":true,"age":"22"}` //put2, err := client.Index().Index("user").BodyString(user2).Do(ctx)// id //if err != nil{ // panic(err) //} //fmt.Printf("Indexed user %s to index %s, type %s
", put2.Id, put2.Index, put2.Type)//Indexed user 4-K2wXIB33YuyEzPYoAi to index user, type _doc
// get1, err := client.Get().Index("user").Id("1").Do(ctx) if err != nil{ panic(err) } if get1.Found{ fmt.Printf("Got document %s in version %d from index %s, type %s
"
, get1.Id, get1.Version, get1.Index, get1.Type) // Got document 1 in version 824633838776 from index user, type _doc } // Flush to make sure the documents got written. //_, err = client.Flush().Index("user").Do(ctx) //if err != nil { // panic(err) //} // "term" Search with a term query //termQuery := elastic.NewTermQuery("name", "mike") //searchResult, err := client.Search(). // Index("user"). // "user" // Query(termQuery). // specify the query // Sort("age", true). // "age" , // From(0).Size(10). // , 10 // Pretty(true). // pretty print request and response JSON json // Do(ctx) // //if err != nil { // // Handle error // panic(err) //} //fmt.Printf("Query took %d milliseconds
", searchResult.TookInMillis)// Query took 3 milliseconds
//var user User // Each , //for _, item1 := range searchResult.Each(reflect.TypeOf(user)) { // if u, ok := item1.(User); ok { // fmt.Printf("Person by %s,age:%d,married:%t,Sex:%s
", u.Name, u.Age, u.Married,u.Sex) //Person by bob,age:23,married:false,Sex:male
// } //} // 2 // hits, //if searchResult.Hits.TotalHits.Value >0{ // fmt.Printf(" %d
", searchResult.Hits.TotalHits.Value)
// for _,hits := range searchResult.Hits.Hits{ // u :=User{} // err := json.Unmarshal([]byte(hits.Source), &u) // if err != nil{ // fmt.Println(" ",err) // } // fmt.Printf("User by %s,age:%d,married:%t,Sex:%s
", u.Name, u.Age, u.Married,u.Sex)
// } //}else { // fmt.Println(" ") //} // update //update, err := client.Update().Index("user").Id("1"). // Script(elastic.NewScriptInline("ctx._source.age += params.num").Lang("painless").Param("num", 1)). // //Upsert(map[string]interface{}{"created": "2020-06-17"}). // value // Do(ctx) //if err != nil { // // Handle error // panic(err) //} //fmt.Printf("New version of user %q is now %d
", update.Id, update.Version)
// 2 //update,err := client.Update().Index("user").Id("1"). // Script(elastic.NewScriptInline("ctx._source.created=params.date").Lang("painless").Param("date","2020-06-17")). // Do(ctx) termQuery := elastic.NewTermQuery("name", "bob") update,err := client.UpdateByQuery("user").Query(termQuery). Script(elastic.NewScriptInline("ctx._source.age += params.num").Lang("painless").Param("num", 1)). Do(ctx) if err != nil{ panic(err) } //fmt.Printf("New version of user %q is now %d
", update.Id, update.Version)
fmt.Println(update) // //termQuery := elastic.NewTermQuery("name", "mike") //_, err = client.DeleteByQuery().Index("user"). // search in index "user" // Query(termQuery). // specify the query // Do(ctx) //if err != nil { // // Handle error // panic(err) //} }

CURD分割解釈
一、作成
1、クライアントの作成
//   :        es      setsniff  ,     docker          
client, err := elastic.NewClient(elastic.SetURL(esUrl), elastic.SetSniff(false))
	if err != nil {
		// Handle error
		panic(err)

2、索引の作成
//   index ,   es                index
	exists, err := client.IndexExists("user").Do(ctx)
	if err != nil {
		panic(err)
	}
	if !exists {
		//      ,   
		createIndex, err := client.CreateIndex("user").BodyString(mapping).Do(ctx)
		if err != nil {
			// Handle error
			panic(err)
		}
		if !createIndex.Acknowledged {
			// Not acknowledged ,    
      fmt.println("Not acknowledged")
		}

3、カスタムドキュメントフィールドtypeの作成
//      index   ,      mapping
_, err = client.PutMapping().Index("user").BodyString(mapping1).Do(ctx)
	if err != nil {
		fmt.Println(err)
		panic(err)
	}

説明:
// mapping  url      ,      
mapping = `
{
	"settings":{
		"number_of_shards": 1,
		"number_of_replicas": 0
	},
	"mappings":{
			"properties":{
				"name":{
					"type":"text"
				},
				"age":{
					"type":"long"
				},
				"married":{
				"type":"boolean"
				},
				"created":{
					"type":"date"
				},
				"tags":{
					"type":"keyword"
				},
				"location":{
					"type":"geo_point"
				},
				"suggest_field":{
					"type":"completion"
				}
		}
	}
}`
 mapping1 = `
{
  "properties": {
    "sex": {
      "type": "text"
    }
  }
}
}`

二、文書の追加
2つの方法で、APIはそれぞれBodyJsonとBodyStringである(観察すると、BodyStringは逆引用符で包まれたes原生文法である)
//       1
	user1 := User{Name:"bob",Sex:"male",Married:false,Age:23}
put1,err:=client.Index().Index("user").BodyJson(user1).Id("1").Do(ctx)
	if err != nil{
		panic(err)
	}
	fmt.Printf("Indexed user %s to index %s, type %s
"
, put1.Id, put1.Index, put1.Type) //Indexed user 1 to index user, type _doc // 2 user2 := `{"name":"mike","sex":"male","married":true,"age":"22"}` put2, err := client.Index().Index("user").BodyString(user2).Do(ctx)// id if err != nil{ panic(err) } fmt.Printf("Indexed user %s to index %s, type

三、照会
//     id  	
get1, err := client.Get().Index("user").Id("1").Do(ctx)
	if err != nil{
		panic(err)
	}
	if get1.Found{
		fmt.Printf("Got document %s in version %d from index %s, type %s
"
, get1.Id, get1.Version, get1.Index, get1.Type) // ,Flush to make sure the documents got written. _, err = client.Flush().Index("user").Do(ctx) if err != nil { panic(err) } // "term" Search with a term query termQuery := elastic.NewTermQuery("name", "mike") searchResult, err := client.Search(). Index("user"). // "user" Query(termQuery). // specify the query Sort("age", true). // "age" , From(0).Size(10). // , 10 Pretty(true). // pretty print request and response JSON json Do(ctx) // if err != nil { // Handle error panic(err) } fmt.Printf("Query took %d milliseconds
"
, searchResult.TookInMillis)// Query took 3 milliseconds var user User Each , for _, item1 := range searchResult.Each(reflect.TypeOf(user)) { if u, ok := item1.(User); ok { fmt.Printf("Person by %s,age:%d,married:%t,Sex:%s
"
, u.Name, u.Age, u.Married,u.Sex) //Person by bob,age:23,married:false,Sex:male } } // 2 // hits, if searchResult.Hits.TotalHits.Value >0{ fmt.Printf(" %d
"
, searchResult.Hits.TotalHits.Value) for _,hits := range searchResult.Hits.Hits{ u :=User{} err := json.Unmarshal([]byte(hits.Source), &u) if err != nil{ fmt.Println(" ",err) } fmt.Printf("User by %s,age:%d,married:%t,Sex:%s
"
, u.Name, u.Age, u.Married,u.Sex) } }else { fmt.Println(" ") }

三、文書の更新
//   id     update
	update, err := client.Update().Index("user").Id("1").
		Script(elastic.NewScriptInline("ctx._source.age += params.num").Lang("painless").Param("num", 1)).
		//Upsert(map[string]interface{}{"created": "2020-06-17"}). //          value
		Do(ctx)
/*
update,err := client.Update().Index("user").Id("1").	Script(elastic.NewScriptInline("ctx._source.created=params.date").Lang("painless").Param("date","2020-06-17")).	Do(ctx)
*/
	if err != nil {
	// Handle error
		panic(err)
	}
	fmt.Printf("New version of user %q is now %d
"
, update.Id, update.Version) // 2 termQuery := elastic.NewTermQuery("name", "bob") update,err := client.UpdateByQuery("user").Query(termQuery). Script(elastic.NewScriptInline("ctx._source.age += params.num").Lang("painless").Param("num", 1)). Do(ctx) if err != nil{ panic(err) } fmt.Printf("New version of user %q is now %d
"
, update.Id, update.Version)

四、削除
//     
termQuery := elastic.NewTermQuery("name", "mike")
	_, err = client.DeleteByQuery().Index("user"). // search in index "user"
		Query(termQuery). // specify the query
		Do(ctx)
	if err != nil {
		// Handle error
		panic(err)
	}
//    id  
_,err = client.Delete().Index("bob").Id("2").Do(ctx)
	if err != nil{
		panic(err)
	}

//     
_,err = client.DeleteIndex("user").Do(ctx)
	if err != nil{
		panic(err)
	}