Skip to content

Instantly share code, notes, and snippets.

@huanghantao
Last active March 20, 2021 12:51
Show Gist options
  • Save huanghantao/87a4580e6ac48952f830dd6f942d8a1b to your computer and use it in GitHub Desktop.
Save huanghantao/87a4580e6ac48952f830dd6f942d8a1b to your computer and use it in GitHub Desktop.

query构造

例子1

"query": {
  "bool": {
    "must": {
      "multi_match": {
        "query": "5833",
        "fields": [
          "Content.SocketInode.*"
        ]
      }
    },
    "filter": {
      "term": {
        "Content.PID": 821
      }
    }
  }
}
multiQuery := elastic.NewMultiMatchQuery("5833", "Content.SocketInode.*")
termQuery := elastic.NewTermQuery("Content.PID", 821)
query := elastic.NewBoolQuery().Filter(termQuery).Must(multiQuery)

scroller例子

type Elastic struct {
	Client   *elastic.Client
}

func (e *Elastic) DoScroll(query *elastic.BoolQuery) []*elastic.SearchHit {
	e.PrepareSearch(query)

	var records []*elastic.SearchHit = nil
	for true {
		ret := e.DoSearch(query)
		if ret == nil {
			// hits returning empty means reaching end.
			break
		}
		for _, i := range ret {
			records = append(records, i)
		}
	}

	return records
}

func (e *Elastic) PrepareSearch(query *elastic.BoolQuery) {
	e.scroller = e.Client.Scroll(e.Cfg.Index).Size(sizePerPage)
	if query != nil {
		e.scroller = e.scroller.Query(query)
	}

	return
}

func (e *Elastic) DoSearch(query *elastic.BoolQuery) []*elastic.SearchHit {
	if query != nil {
		e.scroller = e.scroller.Query(query)
	}
	res, err := e.scroller.Do(context.Background())
	if err == io.EOF {
		return nil
	} else if err != nil {
		log.Fatal(err)
	}

	if res == nil {
		log.Fatal("expected results != nil; got nil")
	}

	if res.Hits == nil {
		log.Error("expected results.Hits != nil; got nil")
	}

	return res.Hits.Hits
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment