Golang中Elasticsearch查询的实现与应用

Golang中Elasticsearch查询的实现与应用 请帮助我将以下Elasticsearch查询转换为Go语言代码:

GET indexabc/_search { “query”: { “multi_match” : { “query”: “page”, “fields”: [ “splunkQuery”, “keywords” , “systemtype”, “url”] } } }

谢谢!

// 示例代码:使用olivere/elastic客户端库构建查询
package main

import (
    "context"
    "fmt"
    "github.com/olivere/elastic/v7"
)

func main() {
    // 创建Elasticsearch客户端
    client, err := elastic.NewClient(elastic.SetURL("http://localhost:9200"))
    if err != nil {
        // 处理错误
        panic(err)
    }

    // 构建multi_match查询
    query := elastic.NewMultiMatchQuery("page", "splunkQuery", "keywords", "systemtype", "url")

    // 执行搜索
    searchResult, err := client.Search().
        Index("indexabc").          // 指定索引
        Query(query).               // 设置查询
        Pretty(true).               // 美化输出
        Do(context.Background())    // 执行
    if err != nil {
        // 处理错误
        panic(err)
    }

    // 处理搜索结果
    fmt.Printf("查询到 %d 条记录\n", searchResult.TotalHits())
}

更多关于Golang中Elasticsearch查询的实现与应用的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于Golang中Elasticsearch查询的实现与应用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


以下是使用 olivere/elastic 客户端库实现该 Elasticsearch 查询的完整代码示例:

package main

import (
    "context"
    "fmt"
    "log"
    "github.com/olivere/elastic/v7"
)

func main() {
    ctx := context.Background()
    
    // 创建Elasticsearch客户端
    client, err := elastic.NewClient(
        elastic.SetURL("http://localhost:9200"),
        elastic.SetSniff(false), // 根据集群配置调整
    )
    if err != nil {
        log.Fatalf("创建客户端失败: %v", err)
    }
    defer client.Stop()

    // 验证连接
    info, code, err := client.Ping("http://localhost:9200").Do(ctx)
    if err != nil {
        log.Fatalf("连接Elasticsearch失败: %v", err)
    }
    fmt.Printf("Elasticsearch返回状态码 %d, 版本 %s\n", code, info.Version.Number)

    // 构建multi_match查询
    multiMatchQuery := elastic.NewMultiMatchQuery("page", 
        "splunkQuery", 
        "keywords", 
        "systemtype", 
        "url",
    )

    // 执行搜索请求
    searchResult, err := client.Search().
        Index("indexabc").      // 指定索引名称
        Query(multiMatchQuery). // 设置查询条件
        Pretty(true).           // 格式化JSON响应
        From(0).                // 分页起始位置
        Size(10).               // 返回结果数量
        Do(ctx)                 // 执行查询
    if err != nil {
        log.Fatalf("查询执行失败: %v", err)
    }

    // 输出查询结果统计
    fmt.Printf("共查询到 %d 条匹配记录\n", searchResult.TotalHits())

    // 遍历并处理查询结果
    if searchResult.TotalHits() > 0 {
        var item map[string]interface{}
        for _, hit := range searchResult.Hits.Hits {
            if err := hit.Source.Unmarshal(&item); err != nil {
                log.Printf("解析结果失败: %v", err)
                continue
            }
            fmt.Printf("文档ID: %s, 分数: %v\n", hit.Id, hit.Score)
            // 访问具体字段
            if url, ok := item["url"].(string); ok {
                fmt.Printf("URL字段: %s\n", url)
            }
        }
    }
}

如果需要更精确的字段权重控制,可以使用 FieldsWithBoost 方法:

// 带权重的multi_match查询
multiMatchQuery := elastic.NewMultiMatchQuery("page").
    FieldWithBoost("splunkQuery", 2.0).   // splunkQuery字段权重加倍
    FieldWithBoost("keywords", 1.5).      // keywords字段权重1.5倍
    Field("systemtype").
    Field("url")

对于需要指定查询类型的场景:

// 指定查询类型(best_fields、most_fields、cross_fields等)
multiMatchQuery := elastic.NewMultiMatchQuery("page", 
    "splunkQuery", "keywords", "systemtype", "url").
    Type("best_fields") // 默认类型

查询结果处理示例(结构体映射):

type Document struct {
    SplunkQuery string `json:"splunkQuery"`
    Keywords    string `json:"keywords"`
    SystemType  string `json:"systemtype"`
    URL         string `json:"url"`
}

// 使用结构体接收结果
var doc Document
for _, hit := range searchResult.Hits.Hits {
    if err := hit.Source.Unmarshal(&doc); err != nil {
        log.Printf("解析失败: %v", err)
        continue
    }
    fmt.Printf("文档内容: %+v\n", doc)
}

确保已安装依赖:

go get github.com/olivere/elastic/v7

这段代码完整实现了您提供的 Elasticsearch 查询,包含连接管理、查询构建、结果处理和错误处理。

回到顶部