Home > Backend Development > Golang > Use Elasticsearch in Go language to achieve efficient search

Use Elasticsearch in Go language to achieve efficient search

王林
Release: 2023-06-15 21:01:40
Original
2069 people have browsed it

With the advent of the big data era, data storage and retrieval have become an important issue we face. Elasticsearch is an open source distributed real-time search and analysis engine. It can search large amounts of data through fast reverse indexing, and provides efficient full-text search, aggregate analysis, real-time monitoring, automatic completion, and data visualization. In practice, It has a wide range of applications in application scenarios. At the same time, as a fast, statically typed programming language, Go language is also widely used in back-end service development. In this article, we will introduce how to use Elasticsearch in Go language to implement efficient search functions.

1. Install Elasticsearch and Go library
First, we need to install Elasticsearch and the corresponding Go library to implement Go's support for the Elasticsearch client. For the installation of Elasticsearch, you can go to the official website of Elasticsearch (https://www.elastic.co/downloads/elasticsearch) to download the corresponding version of the installation package and install it according to the operating system and installation method.

Next, we need to add the Elasticsearch client library to the Go environment. In Go, there are many third-party libraries that support our programming development using the Elasticsearch client. Among them, the more common libraries are:

  1. Elastic (Document address: https://godoc.org/gopkg.in/olivere/elastic.v5)
  2. go-elasticsearch ( Document address: https://github.com/elastic/go-elasticsearch)
  3. golang-elasticsearch (Document address: https://github.com/elastic/go-elasticsearch)

Here we choose Elastic. In Go, you can use the following command to install the Elasticsearch client library:

go get -u gopkg.in/olivere/elastic.v5

2. Connect to Elasticsearch
Connect to Elasticsearch You need to specify the IP and port number of the Elasticsearch server. By default, the port number of Elasticsearch is 9200. You can connect through the following method:

client, err := elastic.NewClient(

elastic.SetURL("http://127.0.0.1:9200"),
elastic.SetSniff(false),
Copy after login

)
if err != nil {

// do something...
Copy after login
Copy after login

}

When creating the Elasticsearch client, you can also make some custom settings, such as the following code:

client, err := elastic.NewClient(

elastic.SetURL("http://127.0.0.1:9200"),
elastic.SetSniff(false),
elastic.SetHealthcheck(true),
elastic.SetGzip(true),
elastic.SetErrorLog(log.New(os.Stderr, "ELASTIC ", log.LstdFlags)),
elastic.SetInfoLog(log.New(os.Stdout, "", log.LstdFlags)),
elastic.SetTraceLog(log.New(ioutil.Discard, "", 0)),
Copy after login

)

Among them, for the settings to connect to Elasticsearch, we have made the following configurations:

  1. SetURL() The method is used to specify the IP and port number of the Elasticsearch server;
  2. SetSniff() method is used to prevent Elastic from automatically discovering the status of other nodes at runtime to obtain cluster health status and other information;
  3. SetHealthcheck () method is used to specify the frequency of health status detection, and a notification will be sent if an abnormality is detected;
  4. SetGzip() method is used to enable the Gzip compression function of the Elasticsearch client;
  5. SetErrorLog() The method is used to specify error log information; the
  6. SetInfoLog() method is used to specify prompt information; the
  7. SetTraceLog() method is used to specify tracking log information.

3. Basic query
After connecting to Elasticsearch, we can perform basic queries on the data in it. The following is a simple query example:

query := elastic.NewMatchQuery("name", "John")
result, err := client.Search().

Index("users").
Query(query).
Do(context.Background())
Copy after login

if err != nil {

// do something...
Copy after login
Copy after login

}
fmt.Printf("Query took %d milliseconds
", result.TookInMillis)

Among them, we used the elastic package The NewMatcQuery() method to create an exact match query, the query field is name, and the query condition is "John". When executing the query, we set the query index to users and specified the query method. Here we use client.Search() to perform the query operation. Finally, we use the result.TookInMillis method to get the time consumed by the query.

4. Advanced query
In actual use, we need to implement more complex query functions, such as range query, fuzzy query, sorting, etc. Elasticsearch supports these capabilities through Query DSL (Query Domain Specific Language). The following are some common query examples:

  1. Full text query

query := elastic.NewMatchQuery("content", "Elasticsearch")

  1. Multi-condition matching query

boolQuery := elastic.NewBoolQuery().Must(

elastic.NewMatchQuery("content", "Elasticsearch"),
elastic.NewRangeQuery("age").Gt("20"),
Copy after login

)

  1. Range query

rangeQuery := elastic.NewRangeQuery("age").Gt("20").Lt("30")

  1. Fuzzy Query

fuzzyQuery := elastic.NewFuzzyQuery("content", "Elasticsearch").

Fuzziness(2).
PrefixLength(1)
Copy after login
  1. sort

sort := elastic.NewFieldSort("age").Asc( )
searchResult, err := client.Search().

Index("users").
Query(boolQuery).
SortBy(sort).
Do(context.Background())
Copy after login

Of course, in actual use, we will use more complex and flexible query methods to obtain the data we need.

5. Paging and Aggregation
When performing data query, we often need to display the data in pages and conduct aggregation query. Elasticsearch also provides query methods that support these operations. The following are some common query examples:

  1. Page query

searchResult, err := client.Search().

Index("users").
Query(boolQuery).
From(0).Size(10).
Do(context.Background())
Copy after login

Among them, From () method is used to set the starting position of the query, and the Size() method is used to set the number of data items returned.

  1. 聚合查询

ageAggs := elastic.NewTermsAggregation().Field("age")
searchResult, err := client.Search().

Index("users").
Query(boolQuery).
Aggregation("age_group", ageAggs).
Do(context.Background())
Copy after login

其中,我们使用了 Elastic 中的 NewTermsAggregation() 方法和 Aggregation() 方法来创建聚合查询。在这个示例中,我们以 "age" 字段作为聚合查询的依据。

六、总结
在本文中,我们介绍了如何在 Go 语言中使用 Elasticsearch 构建一个高效的搜索系统。从连接 Elasticsearch 开始,我们讲解了基础查询、进阶查询、分页和聚合查询等多种查询方式,以及如何使用 Elasticsearch 去提高我们的搜索效率,并给出了部分示例代码。通过阅读本文,您应该可以对 Go 和 Elasticsearch 之间的集成有一个更加深入的理解,应用于实际项目开发中去构建高效的搜索系统。

The above is the detailed content of Use Elasticsearch in Go language to achieve efficient search. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template