Home  >  Article  >  Backend Development  >  Let’s talk about knowledge about querying Elasticsearch in Go language

Let’s talk about knowledge about querying Elasticsearch in Go language

PHPz
PHPzOriginal
2023-04-10 14:18:45934browse

Elasticsearch is an open source distributed search engine that is widely used in various search and data analysis scenarios. At the same time, as an efficient and convenient programming language, Go language is also loved and used by more and more developers. For Elasticsearch's high-performance query and data analysis functions, Go also provides some convenient query libraries and frameworks. This article will introduce in detail the knowledge related to querying Elasticsearch in Go language to help you better implement Elasticsearch query.

1. Introduction to Go language library

Go language already has some mature Elasticsearch query libraries. The following briefly introduces them according to their respective characteristics.

  1. go-elasticsearch

go-elasticsearch is an Elasticsearch client officially launched by Elasticsearch and implemented in Go language. It also includes the query and analysis functions of Elasticsearch. Especially after Elasticsearch 7.x version, go-elasticsearch has become the officially recommended Go language library by Elasticsearch. go-elasticsearch can run on multiple operating system platforms and already supports Elasticsearch 6.x and 7.x versions. For its specific usage, please refer to the official documentation.

  1. go-es

go-es is an Elasticsearch Go client open sourced by Xiaomi. Due to its ease of use and comprehensive functions, it has become a large-scale domestic One of the Elasticsearch client libraries widely used in Internet enterprises. The parameter design of various query APIs in the go-es library is simple and clear, and the syntax is very close to the query syntax of Elasticsearch, so you can directly use the Elasticsearch query DSL for querying. For detailed usage of this library, please refer to its Github repository.

  1. kingim/goes

goes is a simple and easy-to-use Elasticsearch Go client library. It greatly reduces the learning cost of basic Elasticsearch operations and supports both interface and object usage. In addition to query and analysis functions, goes also provides a simple geographical coordinate calculation library that supports the calculation of distance and angle values ​​​​between two longitudes and latitudes. For detailed usage of kingim/goes, please refer to its Github repository.

  1. olivere/elastic

olivere/elastic is the Go client library for Elasticsearch. Similar to go-elasticsearch and go-es, they both provide very convenient query APIs for Elasticsearch. However, olivere/elastic pays more attention to the serialization and deserialization of query results, supports encapsulation and filtering of multiple output formats (such as Json, Xml, etc.), and is suitable for scenarios such as front-end and back-end result interaction. You can check out the olivere/elastic Github repository for more usage details.

2. Query Elasticsearch

In the Go language, through the Elasticsearch Go client library, you can easily perform Elasticsearch related query, search and analysis operations. From the perspective of interface calls, there are some differences in how to use each library, but the basic query functions, syntax and logic are similar. Below we give a few examples to introduce how to query Elasticsearch in Go.

  1. Query all documents

es official documentation recommends the following method:

    Package main
    import (
        "context"
        "fmt"

        "github.com/elastic/go-elasticsearch/v7"
        "github.com/elastic/go-elasticsearch/v7/esapi"
        "github.com/elastic/go-elasticsearch/v7/esutil"
    )

    func main() {
        es, _ := elasticsearch.NewDefaultClient()
        req := esapi.SearchRequest{
            Body:     esutil.NewJSONReader(map[string]interface{}{"query": map[string]interface{}{"match_all": map[string]interface{}{}}}),
            Index:    []string{"my-index-000001"},
            TrackTotalHits: true,
        }
        res, err := req.Do(context.Background(), es)
        fmt.Println(res, err)
    }
  1. Query documents containing a certain word

     q := elastic.NewTermQuery("content", "hello")
     searchResult, err := client.Search().
         Index("twitter").
         Query(q).
         Do(ctx)
     if err != nil {
         log.Fatalln(err)
     }
  2. Query documents within a certain range

     terms := []string{"world", "how", "are", "you"}
     q1 := elastic.NewTermsQuery("content", terms...)
     q2 := elastic.NewRangeQuery("publish_time").Gte("2021-01-01").Lte("2021-02-01")
     query := elastic.NewBoolQuery().Must(q1).Filter(q2)
     searchResult, err := client.Search().
         Index("twitter").
         Query(query).
         From(0).Size(10).
         Do(ctx)
     if err != nil {
         log.Fatalln(err)
     }
  3. Use aggregate functions to implement classification statistics

     agg := elastic.NewTermsAggregation().Field("category").Size(10000)
     query := elastic.NewMatchAllQuery()
     searchResult, err := client.Search().Index("goods").Size(0).Query(query).Aggregation("by_category", agg).Do(ctx)
     if err != nil {
         log.Fatalln(err)
     }
     bucketDateHists := searchResult.Aggregations.Terms("by_category")
     for _, bucket := range bucketDateHists.Buckets {
         fmt.Printf("%v: %d\n", bucket.Key, int(bucket.DocCount))
     }

3. Summary

Through the above introduction, we can see that the Elasticsearch query library provided by the Go language is very rich, and the operation is also very simple and efficient. Whether it is data search or data analysis, the Go language can play an important role. Of course, if you want to have a deeper understanding of Elasticsearch or Go language related knowledge, it is recommended to read more official documents and source code to deepen your understanding and understanding.

The above is the detailed content of Let’s talk about knowledge about querying Elasticsearch in Go language. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn