这里Elasticsearch的数据直接使用了一个开源库 amazonriver (https://github.com/hellobike/amazonriver)将postgresql 数据库中的数据同步了过来
使用了golang的elastic(https://github.com/olivere/elastic)库来操作es
demo 如下:
package main
import (
"fmt"
"context"
"github.com/olivere/elastic"
"encoding/json"
)
type Map map[string]interface{}
func (m Map) SetVal(key string, val interface{}) {
if val == nil {
delete(m, key)
} else {
m[key] = val
}
}
func (m Map) GetVal(key string) interface{} {
value, ok := m[key]
if !ok {
return nil
} else {
return value
}
}
func EsGet() {
Client, err := elastic.NewClient(elastic.SetURL("http://127.0.0.1:9200"))
if err != nil {
fmt.Println("无法连接到es")
return
}
// 根据id 查询
get, err := Client.Get().Index("product_index").Id("19523").Do(context.Background())
if err != nil {
fmt.Println("查询失败", err)
return
}
// 根据名字查询
query := elastic.NewMatchQuery("title", "机械革命")
mi, err := Client.Search().Index("product_index").Query(query).From(0).Size(10).Do(context.Background())
if err != nil {
return
}
source := get.Source
for _, h := range mi.Hits.Hits {
var dict db.Map
err = json.Unmarshal(h.Source, &dict)
if err != nil {
fmt.Println("MatchQuery 错误", err)
return
}
fmt.Println(dict.GetVal("title"))
}
var data Map
err = json.Unmarshal(source, &data)
if err != nil {
return
}
fmt.Println("data", data.GetVal("title"))
fmt.Println(string(source))
// must 相当于 sql 的and 条件查询,terms 相当于 in 条件查询
boolQuery := elastic.NewBoolQuery()
boolQuery.Must(elastic.NewTermQuery("buyer_id", 1), elastic.NewTermsQuery("type", 100,400))
orderResp, err := Client.Search().Index("order_index").Sort("tid", false).Query(boolQuery).From(0).Size(10).Do(context.Background())
if err != nil {
fmt.Println("查询订单失败", err)
return
}
for _, o := range orderResp.Hits.Hits {
var order db.Order
err = json.Unmarshal(o.Source, &order)
if err != nil {
fmt.Println("eeee", err)
}
}
fmt.Println("查询到订单数量 ", len(orderResp.Hits.Hits))
func main() {
EsGet()
}