package elastic import ( "context" "encoding/json" "errors" "fmt" "github.com/olivere/elastic/v7" ) // 首页搜索 func SearchESEnglishReport(keyWord string, from, size int64) (searchResp *elastic.SearchResult, total int64, err error) { indexName := EsEnglishReportIndexName client, err := NewClient() if err != nil { return } var must []map[string]interface{} shouldSub := []map[string]interface{}{ map[string]interface{}{ "match": map[string]interface{}{ "Abstract": map[string]interface{}{ "query": keyWord, //"minimum_should_match": "60%", "boost": 3, }, }, }, map[string]interface{}{ "match": map[string]interface{}{ "BodyContent": map[string]interface{}{ "query": keyWord, //"minimum_should_match": "60%", "boost": 1, }, }, }, map[string]interface{}{ "match": map[string]interface{}{ "Title": map[string]interface{}{ "query": keyWord, //"minimum_should_match": "60%", "boost": 1, }, }, }, map[string]interface{}{ "match_phrase": map[string]interface{}{ "Abstract": map[string]interface{}{ "query": keyWord, //"slop": "50", "boost": 5, }, }, }, map[string]interface{}{ "match_phrase": map[string]interface{}{ "BodyContent": map[string]interface{}{ "query": keyWord, "boost": 3, }, }, }, map[string]interface{}{ "match_phrase": map[string]interface{}{ "Title": map[string]interface{}{ "query": keyWord, "boost": 3, }, }, }, } mustMap := map[string]interface{}{ "bool": map[string]interface{}{ "should": shouldSub, }, } must = append(must, mustMap) filterMust := []map[string]interface{}{ map[string]interface{}{ "term": map[string]interface{}{ "PublishState": 2, //必须是已发布的报告 }, }, } filterMap := map[string]interface{}{ "bool": map[string]interface{}{ "must": filterMust, }, } source := map[string]interface{}{ "query": map[string]interface{}{ "bool": map[string]interface{}{ "must": must, "filter": filterMap, }, }, } source["from"] = from source["size"] = size source["highlight"] = map[string]interface{}{ "fields": map[string]interface{}{ "Abstract": map[string]interface{}{}, "BodyContent": map[string]interface{}{ // "pre_tags" : "{{highlight}}", // "post_tags": "{{/highlight}}", }, "Title": map[string]interface{}{}, }, "pre_tags": "", "post_tags": "", } source["sort"] = []map[string]interface{}{ map[string]interface{}{ "PublishTime.keyword": map[string]interface{}{ "order": "desc", }, }, map[string]interface{}{ "_score": map[string]interface{}{ "order": "desc", }, }, } jsonstr, err := json.Marshal(source) fmt.Printf("%s", jsonstr) request := client.Search(indexName).Source(source) // sets the JSON request //requestJson, err := json.Marshal(request) //if err != nil { // fmt.Println("requestJson err:", err) //} //fmt.Println("requestJson ", string(requestJson) searchResp, err = request.Do(context.Background()) if err != nil { fmt.Print("结果err:") fmt.Println(err.Error()) return } fmt.Print("结果正常:") fmt.Println(searchResp.Status) if searchResp.Status != 0 { err = errors.New("查询失败") } total = searchResp.TotalHits() return }