search
HomeBackend DevelopmentGolangHow to develop an application for ES retrieval using Golang

With the rapid development of Internet applications, massive data has become a norm, and efficient storage and query of these data have become very important. Search Engine is an efficient and scalable distributed retrieval engine for large-scale distributed data storage environments. It is a technology oriented to the field of text retrieval.

ElasticSearch (ES) is a search engine developed based on the Lucene library. It is a distributed full-text search engine based on RESTful architecture that can support real-time search, data analysis and other functions. Due to its open source nature and ease of use, ElasticSearch is increasingly favored by developers. This article will introduce how to use Golang to develop applications for ES retrieval.

First, we need to install the ES client in the Go programming language. The client of ES uses a RESTful architecture, so we can use Go's HTTP request library to interact with ES. Then, we can refer to the following code example to call the ES RESTful API to implement a simple search:

package main

import (
    "encoding/json"
    "fmt"
    "net/http"
    "bytes"
)

type SearchResult struct {
    Hits struct {
        Total int `json:"total"`
        Hits []struct {
            Source interface{} `json:"_source"`
        } `json:"hits"`
    } `json:"hits"`
}

func main() {
    query := "hello"
    url := fmt.Sprintf("http://localhost:9200/_search?q=%s", query)
    resp, _ := http.Get(url)
    defer resp.Body.Close()
    var result SearchResult
    json.NewDecoder(resp.Body).Decode(&result)
    b, _ := json.Marshal(result.Hits.Hits)
    fmt.Println(string(b))
}

First, we define a structure named SearchResult to store ES search results. Then, we used the fmt.Sprintf function to construct the search URL, submitted the request to ES through the http.Get function, and parsed the result into the structure.

Finally, we serialize the results to JSON format and print to the console. In this way, we can use Go language to search documents in ES very simply.

However, this method is only suitable for simple search applications. For operations that require richer functions such as search by conditions or aggregation, we need to use the Golang client officially provided by ES: go-elasticsearch.

First, we need to install the officially provided go-elasticsearch library. You can use the following command to install:

go get github.com/elastic/go-elasticsearch/v8

Next, we use the following code example to implement ES query :

package main

import (
    "context"
    "fmt"
    "github.com/elastic/go-elasticsearch/v8"
    "github.com/elastic/go-elasticsearch/v8/esapi"
    "encoding/json"
    "bytes"
)

type SearchResult struct {
    Hits struct {
        Total int `json:"total"`
        Hits []struct {
            Source interface{} `json:"_source"`
        } `json:"hits"`
    } `json:"hits"`
}

func main() {
    es, err := elasticsearch.NewDefaultClient()
    if err != nil {
        fmt.Println("Error creating Elasticsearch client:", err)
        return
    }

    query := "hello"

    var buf bytes.Buffer
    queryMap := map[string]interface{}{
        "query": map[string]interface{}{
            "match": map[string]interface{}{
                "message": query,
            },
        },
    }
    if err := json.NewEncoder(&buf).Encode(queryMap); err != nil {
        fmt.Println("Error encoding query:", err)
        return
    }

    req := esapi.SearchRequest{
        Index: []string{"my_index"},
        Body:  &buf,
        Pretty: true,
    }

    res, err := req.Do(context.Background(), es)
    if err != nil {
        fmt.Println("Error searching for documents:", err)
        return
    }
    defer res.Body.Close()

    var result SearchResult
    json.NewDecoder(res.Body).Decode(&result)
    b, _ := json.Marshal(result.Hits.Hits)
    fmt.Println(string(b))
}

First, we create an Elasticsearch client and then define the query keywords. Next, we construct a map in JSON format containing query conditions and encode it into buf through the json.NewEncoder function.

Finally, we use the ES API provided by the go-elasticsearch library to send query requests to ES, and read and parse the request responses.

Using the go-elasticsearch library can easily implement complex ES search functions and make the code more elegant and simple. Using Golang for ES search greatly improves search speed while maintaining code efficiency.

In short, Golang is a concise and efficient programming language, and it is very easy to use it to implement ES search. I hope this article can help you understand the use of ES search and go-elasticsearch library.

The above is the detailed content of How to develop an application for ES retrieval using Golang. 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
Go language pack import: What is the difference between underscore and without underscore?Go language pack import: What is the difference between underscore and without underscore?Mar 03, 2025 pm 05:17 PM

This article explains Go's package import mechanisms: named imports (e.g., import "fmt") and blank imports (e.g., import _ "fmt"). Named imports make package contents accessible, while blank imports only execute t

How to implement short-term information transfer between pages in the Beego framework?How to implement short-term information transfer between pages in the Beego framework?Mar 03, 2025 pm 05:22 PM

This article explains Beego's NewFlash() function for inter-page data transfer in web applications. It focuses on using NewFlash() to display temporary messages (success, error, warning) between controllers, leveraging the session mechanism. Limita

How to convert MySQL query result List into a custom structure slice in Go language?How to convert MySQL query result List into a custom structure slice in Go language?Mar 03, 2025 pm 05:18 PM

This article details efficient conversion of MySQL query results into Go struct slices. It emphasizes using database/sql's Scan method for optimal performance, avoiding manual parsing. Best practices for struct field mapping using db tags and robus

How do I write mock objects and stubs for testing in Go?How do I write mock objects and stubs for testing in Go?Mar 10, 2025 pm 05:38 PM

This article demonstrates creating mocks and stubs in Go for unit testing. It emphasizes using interfaces, provides examples of mock implementations, and discusses best practices like keeping mocks focused and using assertion libraries. The articl

How can I define custom type constraints for generics in Go?How can I define custom type constraints for generics in Go?Mar 10, 2025 pm 03:20 PM

This article explores Go's custom type constraints for generics. It details how interfaces define minimum type requirements for generic functions, improving type safety and code reusability. The article also discusses limitations and best practices

How to write files in Go language conveniently?How to write files in Go language conveniently?Mar 03, 2025 pm 05:15 PM

This article details efficient file writing in Go, comparing os.WriteFile (suitable for small files) with os.OpenFile and buffered writes (optimal for large files). It emphasizes robust error handling, using defer, and checking for specific errors.

How do you write unit tests in Go?How do you write unit tests in Go?Mar 21, 2025 pm 06:34 PM

The article discusses writing unit tests in Go, covering best practices, mocking techniques, and tools for efficient test management.

How can I use tracing tools to understand the execution flow of my Go applications?How can I use tracing tools to understand the execution flow of my Go applications?Mar 10, 2025 pm 05:36 PM

This article explores using tracing tools to analyze Go application execution flow. It discusses manual and automatic instrumentation techniques, comparing tools like Jaeger, Zipkin, and OpenTelemetry, and highlighting effective data visualization

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)