golang 操作 Elasticsearch

这里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()
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值