An apple a day keeps the doctor away !

0%

golang 查询elasticsearch取值

连接es

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package main

import (
"context"
"fmt"

"github.com/olivere/elastic"
)

var client *elastic.Client
var host = "http://x.x.x.x:29200/"

func init() {
fmt.Println("开始初始化")

var err error

// 不添加elastic.SetSniff(false)会导致连不上
client, err = elastic.NewClient(elastic.SetSniff(false), elastic.SetURL(host))
if err != nil {
panic(err)
}

info, _, err := client.Ping(host).Do(context.Background())
if err != nil {
panic(err)
}
fmt.Printf("version %s\n", info.Version.Number)
fmt.Println("初始化完成,连接成功")
}

使用bool查询

1
2
3
4
5
6
7
8
9
10
11
12
13
func query(department_name, department_id string) {
ids := "1.1007588.1327." + department_id

// boolQuery
boolQuery := elastic.NewBoolQuery()
boolQuery.Must(elastic.NewPrefixQuery("SZDXFJG.XFJGNBBM", ids))
searchResult, err := client.Search().Index("a_kec_pbjl").Query(boolQuery).Do(context.Background())
if err != nil {
fmt.Println("查询失败")
}
fmt.Println(department_name, searchResult.Hits.TotalHits)

}