How to use Golang for Elasticsearch query operations

PHPz
Release: 2023-04-11 10:07:44
Original
1241 people have browsed it

With the advent of the big data era, the demand for data storage and query is also increasing. Elasticsearch is currently a popular distributed search engine that provides a relatively simple and easy-to-use RESTful API. As an efficient programming language, Golang is loved by more and more developers. This article will introduce how to use Golang to perform Elasticsearch query operations.

1. Dependent library installation

In Golang, we need to use a third-party library to perform Elasticsearch related operations. It is recommended to use the officially provided github.com/elastic/go-elasticsearch library.

To install this library, just run the following command in the terminal:

go get github.com/elastic/go-elasticsearch
Copy after login

If your computer cannot access github.com, please refer to the following steps:

1. Visit https://github.com/elastic/go-elasticsearch and download the zip file locally.

2. Unzip the zip file to a directory.

3. Move the decompressed directory to the GOPATH directory under your project directory.

4. Run the following command in the terminal:

cd $GOPATH/go-elasticsearch
go install
Copy after login

This process may be time-consuming, please wait patiently.

2. Establish an Elasticsearch connection

To perform Elasticsearch queries, we need to establish a connection first. In Golang, you first need to introduce the github.com/elastic/go-elasticsearch library, and then use the NewDefaultClient method to establish a connection.

import (
    "fmt"
    "github.com/elastic/go-elasticsearch"
    "log"
)

func main() {
    cfg := elasticsearch.Config{
        Addresses: []string{
            "http://localhost:9200",
        },
    }
    es, err := elasticsearch.NewClient(cfg)
    if err != nil {
        log.Fatalf("连接 Elasticsearch 失败:%s", err)
    }
    fmt.Println("连接 Elasticsearch 成功")
}
Copy after login

Here we specify the address of Elasticsearch as http://localhost:9200. If your Elasticsearch runs on another address, please modify the address.

3. Query Elasticsearch data

After establishing the connection, you can perform Elasticsearch query operations. We can complete the Elasticsearch query operation by sending HTTP requests through the http library in Golang and receiving the response content.

Take all the data where the message field under the query index test_index contains the hello string as an example:

import (
    "bytes"
    "encoding/json"
    "fmt"
    "github.com/elastic/go-elasticsearch"
    "github.com/elastic/go-elasticsearch/esapi"
    "io/ioutil"
    "log"
    "net/http"
    "strings"
)

func main() {
    cfg := elasticsearch.Config{
        Addresses: []string{
            "http://localhost:9200",
        },
    }
    es, err := elasticsearch.NewClient(cfg)
    if err != nil {
        log.Fatalf("连接 Elasticsearch 失败:%s", err)
    }
    fmt.Println("连接 Elasticsearch 成功")

    var (
        r map[string]interface{}
        b bytes.Buffer
    )

    query := map[string]interface{}{
        "query": map[string]interface{}{
            "match": map[string]interface{}{
                "message": "hello",
            },
        },
    }

    if err := json.NewEncoder(&b).Encode(query); err != nil {
        log.Fatalf("无法编码查询:%s", err)
    }

    req, _ := http.NewRequest("GET", "/test_index/_search", &b)
    req.Header.Add("Content-Type", "application/json")

    res, err := es.Perform(req)
    if err != nil {
        log.Fatalf("查询 Elasticsearch 失败:%s", err)
    }

    defer res.Body.Close()

    if res.IsError() {
        var r map[string]interface{}
        if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
            log.Fatalf("响应错误:%s", err)
        } else {
            // 响应错误信息
            log.Fatalf("响应错误:%s", r["error"].(map[string]interface{})["reason"])
        }
    }

    if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
        log.Fatalf("响应结果解析失败:%s", err)
    }

    results := r["hits"].(map[string]interface{})["hits"].([]interface{})
    fmt.Printf("共找到 %d 条匹配结果:\n", len(results))
    for _, result := range results {
        message := result.(map[string]interface{})["_source"].(map[string]interface{})["message"].(string)
        fmt.Printf("%s\n", message)
    }
}
Copy after login

Here we First, a query condition is defined, that is, the message field contains the hello string. Then use Golang's http library to create an HTTP request and put the query conditions in the request body. Then use the es.Perform method to send the request and receive the response result.

If the response result is wrong, we can get the error information by parsing the JSON data. If there are no errors in the response, we print the query results in the terminal.

It should be noted that here we use the GET method to send a query request. In fact, Elasticsearch supports a variety of different query request methods, including GET, POST, PUT, etc. For specific query methods and syntax, please refer to the Elasticsearch official documentation.

The method introduced in this article is based on Elasticsearch's RESTful API. In addition, Elasticsearch also provides a more flexible and efficient query method, using its officially provided Golang library github.com/olivere/elastic. If you have more efficient query requirements, consider using this library.

In short, it is very convenient and fast to use Elasticsearch for query in Golang. Only a few lines of code are needed to implement powerful data query functions. It is recommended that developers pay more attention to Elasticsearch related technologies and improve their data storage and query capabilities.

The above is the detailed content of How to use Golang for Elasticsearch query operations. For more information, please follow other related articles on the PHP Chinese website!

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