【GO】11.elasticsearch Golang olivere/elastic

6014 ワード

  • Golangオペレーションelasticsearchサードパーティライブラリ
  • github.com/olivere/elastic
     
  • エンティティークラス
  • を追加
    自分で実体クラスをテストするのは簡単で、仕事中の実体インスタンスは直接持ってきて使って、実体オブジェクトは少し複雑です
    package entities
    
    import "fmt"
    
    type Result struct {
    	Geometry       Geometry       `json:"geometry"`
    	Icon           string         `json:"icon"`
    	Id             string         `json:"id"`
    	Name           string         `json:"name"`
    	Photos         []*Photo       `json:"photos"`
    	PlaceId        string         `json:"place_id"`
    	Reference      string         `json:"reference"`
    	Scope          string         `json:"scope"`
    	Types          []string       `json:"types"`
    	Vicinity       string         `json:"vicinity"`
    	LocationSearch LocationSearch `json:"location_search"`
    }
    
    func (e *Result) String() string {
    	return fmt.Sprintf("%+v", *e)
    }
    
    type Geometry struct {
    	Location Location `json:"location"`
    	Viewport Viewport `json:"viewport"`
    }
    
    func (e *Geometry) String() string {
    	return fmt.Sprintf("%+v", *e)
    }
    
    type Location struct {
    	Lat float64 `json:"lat"`
    	Lng float64 `json:"lng"`
    }
    
    func (e *Location) String() string {
    	return fmt.Sprintf("%+v", *e)
    }
    
    type LocationSearch struct {
    	Lat float64 `json:"lat"`
    	Lon float64 `json:"lon"`
    }
    
    func (e *LocationSearch) String() string {
    	return fmt.Sprintf("%+v", *e)
    }
    
    type Viewport struct {
    	Northeast Location `json:"northeast"`
    	Southwest Location `json:"southwest"`
    }
    
    func (e *Viewport) String() string {
    	return fmt.Sprintf("%+v", *e)
    }
    
    type Photo struct {
    	Height           int      `json:"height"`
    	HtmlAttributions []string `json:"html_attributions"`
    	PhotoReference   string   `json:"photo_reference"`
    	Width            int      `json:"width"`
    }
    
    func (e *Photo) String() string {
    	return fmt.Sprintf("%+v", *e)
    }
    
  • コードインスタンス
  • package main
    
    import (
    	"context"
    	"encoding/json"
    	"entities"
    	"fmt"
    
    	"github.com/olivere/elastic"
    )
    
    var client *elastic.Client
    var host = "http://127.0.0.1:9200/"
    
    func main() {
    	//   es Client
    	err := initESClient()
    
    	if err != nil {
    		fmt.Printf("create es client failed | err : %s
    ", err) return } // es nearbyObj := entities.Result{Id: "bbb", Icon: "ccc", Name: "name"} addRep, err := addESItem(nearbyObj, nearbyObj.Id) if err != nil { fmt.Printf("create es data failed | err : %s
    ", err) return } fmt.Printf("%+v
    ", *addRep) // id es getRep, err := getESItem(nearbyObj.Id) if err != nil{ fmt.Printf("get es data failed | err : %s
    ", err) return } fmt.Printf("get rep : %+v
    ", *getRep) fmt.Printf("get rep source : %s
    ", string(getRep.Source)) // newNearby := &entities.Result{} err = json.Unmarshal(getRep.Source, newNearby) if err == nil { fmt.Printf("get source json unmarshal to nearby : %+v
    ", *newNearby) } // es searchRep, err := searchESItem() if err != nil{ fmt.Printf("search es data failed | err : %s
    ", err) return } fmt.Printf("get rep : %s
    ", searchRep.Hits.Hits[0].Source) // es delRep, err := deleteESItem(nearbyObj.Id) if err != nil { fmt.Printf("delete es data failed | err : %s
    ", err) return } fmt.Printf("%+v
    ", *delRep) client.Stop() } // es func initESClient() (err error) { client, err = elastic.NewClient( elastic.SetURL(host), ) if err != nil { fmt.Printf("can't connect to elasticsearch | err : %s
    ", err) return } fmt.Println("connect to elasticsearch success") return } // es func addESItem(body interface{}, id string) (rep *elastic.IndexResponse, err error) { rep, err = client.Index(). Index("poi"). Id(id). BodyJson(body). Do(context.Background()) return } // func getESItem(id string) (rep *elastic.GetResult, err error) { rep, err = client.Get(). Index("poi"). Id(id). Do(context.Background()) return } // func searchESItem()(rep *elastic.SearchResult, err error){ q := elastic.NewQueryStringQuery("icon:ccc") rep, err = client.Search("poi"). Query(q). Do(context.Background()) return } // func deleteESItem(id string) (rep *elastic.DeleteResponse, err error) { rep, err = client.Delete(). Index("poi"). Id(id). Do(context.Background()) return } // geo func QueryElasticSearch(name, lat, lng string, pageSize int) { floatLat, err := strconv.ParseFloat(lat, 64) if err != nil { return } floatLng, err := strconv.ParseFloat(lng, 64) if err != nil { return } names := strings.Fields(name) //bool boolSearch := elastic.NewBoolQuery() // floatLat,floatLng 20km boolSearch.Filter(elastic.NewGeoDistanceQuery("location_search").Distance("20km").Lat(floatLat).Lon(floatLng)) // name vicinity ,should " " mustSearch := elastic.NewBoolQuery() for _, data := range names { mustSearch.Should(elastic.NewMatchQuery("name", data)) mustSearch.Should(elastic.NewMatchQuery("vicinity", data)) } //must " " boolSearch.Must(mustSearch) res, err := client.Search("poi"). Query(boolSearch). From(0). Size(pageSize). SortBy(elastic.NewGeoDistanceSort("location_search").Point(floatLat, floatLng)). Do(context.Background()) if err != nil { return } var typ *entities.Result // , , for _, item := range res.Each(reflect.TypeOf(typ)) { result := item.(*entities.Result) fmt.Println(result) } return }
  • ネスト属性クエリー使用点.

  • Geometry属性の下でLocationのLatが111に等しいことを検索するには、次のように書きます.
    Geometry.Location.Lat:111