示例#1
0
文件: elastic.go 项目: noblehng/bosun
func ESAll(e *State, T miniprofiler.Timer) (*Results, error) {
	var r Results
	q := ESQuery{
		Query: elastic.NewMatchAllQuery(),
	}
	r.Results = append(r.Results, &Result{Value: q})
	return &r, nil
}
示例#2
0
func ExampleSearchResult() {
	client, err := elastic.NewClient()
	if err != nil {
		panic(err)
	}

	// Do a search
	searchResult, err := client.Search().Index("twitter").Query(elastic.NewMatchAllQuery()).Do()
	if err != nil {
		panic(err)
	}

	// searchResult is of type SearchResult and returns hits, suggestions,
	// and all kinds of other information from Elasticsearch.
	fmt.Printf("Query took %d milliseconds\n", searchResult.TookInMillis)

	// Each is a utility function that iterates over hits in a search result.
	// It makes sure you don't need to check for nil values in the response.
	// However, it ignores errors in serialization. If you want full control
	// over iterating the hits, see below.
	var ttyp Tweet
	for _, item := range searchResult.Each(reflect.TypeOf(ttyp)) {
		t := item.(Tweet)
		fmt.Printf("Tweet by %s: %s\n", t.User, t.Message)
	}
	fmt.Printf("Found a total of %d tweets\n", searchResult.TotalHits())

	// Here's how you iterate hits with full control.
	if searchResult.Hits.TotalHits > 0 {
		fmt.Printf("Found a total of %d tweets\n", searchResult.Hits.TotalHits)

		// Iterate through results
		for _, hit := range searchResult.Hits.Hits {
			// hit.Index contains the name of the index

			// Deserialize hit.Source into a Tweet (could also be just a map[string]interface{}).
			var t Tweet
			err := json.Unmarshal(*hit.Source, &t)
			if err != nil {
				// Deserialization failed
			}

			// Work with tweet
			fmt.Printf("Tweet by %s: %s\n", t.User, t.Message)
		}
	} else {
		// No hits
		fmt.Print("Found no tweets\n")
	}
}
示例#3
0
func ExampleAggregations() {
	// Get a client to the local Elasticsearch instance.
	client, err := elastic.NewClient()
	if err != nil {
		// Handle error
		panic(err)
	}

	// Create an aggregation for users and a sub-aggregation for a date histogram of tweets (per year).
	timeline := elastic.NewTermsAggregation().Field("user").Size(10).OrderByCountDesc()
	histogram := elastic.NewDateHistogramAggregation().Field("created").Interval("year")
	timeline = timeline.SubAggregation("history", histogram)

	// Search with a term query
	searchResult, err := client.Search().
		Index("twitter").                  // search in index "twitter"
		Query(elastic.NewMatchAllQuery()). // return all results, but ...
		SearchType("count").               // ... do not return hits, just the count
		Aggregation("timeline", timeline). // add our aggregation to the query
		Pretty(true).                      // pretty print request and response JSON
		Do()                               // execute
	if err != nil {
		// Handle error
		panic(err)
	}

	// Access "timeline" aggregate in search result.
	agg, found := searchResult.Aggregations.Terms("timeline")
	if !found {
		log.Fatalf("we sould have a terms aggregation called %q", "timeline")
	}
	for _, userBucket := range agg.Buckets {
		// Every bucket should have the user field as key.
		user := userBucket.Key

		// The sub-aggregation history should have the number of tweets per year.
		histogram, found := userBucket.DateHistogram("history")
		if found {
			for _, year := range histogram.Buckets {
				fmt.Printf("user %q has %d tweets in %q\n", user, year.DocCount, year.KeyAsString)
			}
		}
	}
}
示例#4
0
// Searches for mssages
func (e *Elastic) GetMessages(q *storage.SearchQuery) (result *storage.SearchResult, err error) {
	var (
		filters []es.Query    = []es.Query{}
		query   *es.BoolQuery = es.NewBoolQuery()
		tsRange *es.RangeQuery
		msg     *storage.Message
	)

	if len(q.Query) > 0 {
		filters = append(filters, es.NewQueryStringQuery(q.Query))
	} else {
		filters = append(filters, es.NewMatchAllQuery())
	}

	if q.From.Second() > 0 && q.To.Second() > 0 {
		tsRange = es.NewRangeQuery("timestamp")
		tsRange = tsRange.From(q.From)
		tsRange = tsRange.To(q.To)
		filters = append(filters, tsRange)
	} else if q.From.Second() > 0 && q.To.Second() <= 0 {
		tsRange = es.NewRangeQuery("timestamp")
		tsRange = tsRange.From(q.From)
		filters = append(filters, tsRange)
	} else if q.To.Second() > 0 && q.From.Second() <= 0 {
		tsRange = es.NewRangeQuery("timestamp")
		tsRange = tsRange.To(q.To)
		filters = append(filters, tsRange)
	}

	rs, err := e.client.
		Search(e.indexName).
		Type(e.typeName).
		Query(query.Filter(filters...)).
		Sort("timestamp", false).
		From(q.Offset).
		Size(q.Limit).
		Do()

	if err != nil {
		return nil, err
	}

	result = &storage.SearchResult{
		Total:    rs.TotalHits(),
		TookMs:   rs.TookInMillis,
		Limit:    q.Limit,
		Offset:   q.Offset,
		Messages: []storage.Message{},
	}

	// rs.Each() is not used because we need to add message id manually
	if rs.Hits != nil && rs.Hits.Hits != nil && len(rs.Hits.Hits) > 0 {
		for _, hit := range rs.Hits.Hits {
			msg = new(storage.Message)
			err = json.Unmarshal(*hit.Source, msg)

			if err != nil {
				continue
			}

			msg.Id = hit.Id

			result.Messages = append(result.Messages, *msg)
		}
	}

	return result, nil
}