Go项目优化——使用Elasticsearch搜索引擎

本文涉及的产品
检索分析服务 Elasticsearch 版,2核4GB开发者规格 1个月
简介: Go项目优化——使用Elasticsearch搜索引擎

案例:

http准备

util/http.go

用于向es服务器发送json格式的Put和Post请求

package util
import (
  "errors"
  "github.com/astaxie/beego/httplib"
  "github.com/bitly/go-simplejson"
  "io"
  "time"
)
// HttpPutJson
// @Title HttpPutJson
// @Description 用于向es服务器发送put请求(新建索引or添加文档)
func HttpPutJson(url, body string) error {
  resp, err := httplib.Put(url).
    Header("Content-Type", "application/json").
    SetTimeout(10*time.Second, 10*time.Second).
    Body(body).
    Response()
  if err == nil {
    defer resp.Body.Close()
    // 不正常的响应状态码
    if resp.StatusCode >= 300 || resp.StatusCode < 200 {
      // es会将错误信息写在body里 打印错误信息
      bodyErr, _ := io.ReadAll(resp.Body)
      body = string(bodyErr)
      err = errors.New(resp.Status + ";" + body)
    }
  }
  return err
}
// HttpPostJson
// @Title HttpPostJson
// @Description 用于向es服务器请求数据,查询数据
// @Param url string
// @Param body string 条件
// @Return *simplejson.Json es服务器返回的信息
func HttpPostJson(url, body string) (*simplejson.Json, error) {
  resp, err := httplib.Post(url).
    Header("Content-Type", "application/json").
    SetTimeout(10*time.Second, 10*time.Second).
    Body(body).
    Response()
  var sj *simplejson.Json
  if err == nil {
    defer resp.Body.Close()
    // 不正常的响应状态码
    if resp.StatusCode >= 300 || resp.StatusCode < 200 {
      bodyErr, _ := io.ReadAll(resp.Body)
      body = string(bodyErr)
      err = errors.New(resp.Status + ";" + body)
    } else {
      bodyBytes, _ := io.ReadAll(resp.Body)
      sj, err = simplejson.NewJson(bodyBytes)
    }
  }
  return sj, err
}

案例(新增):

建立索引+添加文档

发布图书的时候为图书和章节文档内容建立索引。

models/elasticSearch.go

package models
import (
  "es.study/util"
  "fmt"
  "github.com/PuerkitoBio/goquery"
  "github.com/astaxie/beego/logs"
  "strconv"
  "strings"
)
var (
  // (应写在配置文件里)搜索引擎配置,后面要加'/'
  elasticHost = "http://localhost:9200/"
)
// ElasticBuildIndex
// localhost:9200/index/_doc/doc_id
// index: 索引 对应sql里的表
// _doc: 文档类型,ES 7.0 以后的版本 已经废弃文档类型了,一个 index 中只有一个默认的 type,即 _doc。
// @Title ElasticBuildIndex
// @Description  指定id的图书增加索引
// @Author hyy 2022-10-14 21:06:27
// @Param bookId int 图书 id
func ElasticBuildIndex(bookId int) {
  // func(m *Book) Select(filed string, value interface{}, cols ...string)
  // SELECT [cols...] FROM books WHERE filed=value;
  book, _ := NewBook().Select("book_id", bookId, "book_id", "book_name", "description")
  addBookToIndex(book.BookId, book.BookName, book.Description)
  // index document
  var documents []Document
  fields := []string{"document_id", "book_id", "document_name", "release"}
  GetOrm("r").QueryTable(TNDoucments()).Filter("book_id", bookId).All(documents, fields...)
  if len(documents) > 0 {
    for _, document := range documents {
      // release: 已发布的章节
      addDocumentToIndex(document.DocumentId, document.BookId, flatHtml(document.Release))
    }
  }
}
// addBookToIndex
// @Title addBookToIndex
// @Description 向图书索引(相当于图书表)中,添加图书
// @Author hyy 2022-10-14 21:07:38
// @Param bookId int 图书id
// @Param bookName string 图书名
// @Param description string 图书描述
func addBookToIndex(bookId int, bookName, description string) {
  queryJson := `
    {
      "book_id":%v,
      "book_name":"%v",
      "description":"%v"
    }
  `
  // ElasticSearch API
  host := elasticHost
  api := host + "mbooks/_doc/" + strconv.Itoa(bookId)
  // 发起请求:
  queryJson = fmt.Sprintf(queryJson, bookId, bookName, description)
  err := util.HttpPutJson(api, queryJson)
  if err != nil {
    logs.Debug(err)
  }
}
// addDocumentToIndex
// @Title addDocumentToIndex
// @Description  向章节文档索引(相当于章节文档表)中,添加章节文档
// @Author hyy 2022-10-14 21:09:09
// @Param documentId int 文档id
// @Param bookId int 所属图书id
// @Param release string 文档发布内容
func addDocumentToIndex(documentId, bookId int, release string) {
  queryJson := `
    {
      "document:_id":%v,
      "book_id":%v,
      "release":"%v"
    }
  `
  // ElasticSearch API
  host := elasticHost
  api := host + "mdocument/_doc/" + strconv.Itoa(documentId)
  // 发起请求:
  queryJson = fmt.Sprintf(queryJson, documentId, bookId, release)
  err := util.HttpPutJson(api, queryJson)
  if err != nil {
    logs.Debug(err)
  }
}
// flatHtml
// 剔除章节里的html标签,取出文本
func flatHtml(htmlStr string) string {
  htmlStr = strings.Replace(htmlStr, "\n", " ", -1)
  htmlStr = strings.Replace(htmlStr, "\"", "", -1)
  gq, err := goquery.NewDocumentFromReader(strings.NewReader(htmlStr))
  // 如果不为空,说明没有
  if err != nil {
    return htmlStr
  }
  return gq.Text()
}

在发布图书的时候,调用ElasticBuildIndex(bookId)接口,将图书信息以及章节内容添加到es中。

案例(查询):

搜索图书:

package models
import (
  "es.study/util"
  "fmt"
  "github.com/PuerkitoBio/goquery"
  "github.com/astaxie/beego/logs"
  "strconv"
  "strings"
)
var (
  // (应写在配置文件里)搜索引擎配置,后面要加'/'
  elasticHost = "http://localhost:9200/"
)
// ... 新增索引or添加文档
// ElasticSearchBook
// localhost:9200/index/_doc/_search
// index: 索引 对应sql里的表
// _doc: 文档类型,ES 7.0 以后的版本 已经废弃文档类型了,一个 index 中只有一个默认的 type,即 _doc。
// @Title ElasticSearchBook
// @Description 根据关键字搜索图书,获取图书的id
// @Author hyy 2022-10-14 20:49:37
// @Param kw string 关键字
// @Param pageSize int 页大小
// @Param page int 页码(可选)
// @Return []int bookId的数组
// @Return int 书的总数
// @Return error 错误
func ElasticSearchBook(kw string, pageSize, page int) ([]int, int, error) {
  var bookIds []int
  count := 0
  if page > 0 {
    // 第一页对应搜索引擎里的第0页
    page = page - 1
  } else {
    page = 0
  }
  queryJson := `
    {
      "query":{
        "multi_match":{
          "query":"%v",
          "fields":["bookName","description"]
        }
      },
      "_source":["book_id"],
      "size":%v,
      "from":%v
    }
  `
  // elasticSearch api
  host := elasticHost
  api := host + "mbook/_doc/_search"
  queryJson = fmt.Sprintf(queryJson, kw, pageSize, page)
  sj, err := util.HttpPostJson(api, queryJson)
  if err == nil {
    count = sj.GetPath("hits", "total").MustInt()
    resultArray := sj.GetPath("hits", "hits").MustArray()
    for _, result := range resultArray {
      if eachMap, ok := result.(map[string]interface{}); ok {
        id, _ := strconv.Atoi(eachMap["_id"].(string))
        bookIds = append(bookIds, id)
      }
    }
  }
  return bookIds, count, err
}
// ElasticSearchDocument
// @Title ElasticSearchDocument
// @Description 根据关键字搜索章节文档,返回章节文档的id,
// 该函数提供两种搜索:
//  1. 搜所有图书的章节文档
//  2. 搜某一本图书的章节文档,所以有个可选参数bookId
//
// @Author hyy 2022-10-14 20:56:54
// @Param kw string 关键字
// @Param pageSize int 页大小
// @Param page int 页码
// @Param bookId ...int 图书id(可选)
// @Return []int 章节文档的id数组
// @Return int 总数
// @Return error 错误
func ElasticSearchDocument(kw string, pageSize, page int, bookId ...int) ([]int, int, error) {
  var documentIds []int
  count := 0
  if page > 0 {
    // 第一页对应搜索引擎里的第0页
    page = page - 1
  } else {
    page = 0
  }
  queryJson := `
    {
      "query":{
        "match":{
          "release":"%v",
        } 
      },
      "_source":["document_id"],
      "size":%v,
      "from":%v
    }
  `
  queryJson = fmt.Sprintf(queryJson, kw, pageSize, page)
  if len(bookId) > 0 && bookId[0] > 0 {
    queryJson = `
      {
        "query":{
          "bool":{
            "filter":[{
              "term":{
                "book_id":%v
              }
            }],
            "must":{
              "multi_match":{
                "query":"%v",
                "fields":["release"]
              }
            }
          } 
        },
        "_source":["document_id"],
        "size":%v,
        "from":%v
      }
    `
    queryJson = fmt.Sprintf(queryJson, kw, pageSize, page)
  }
  // elasticSearch api
  host := elasticHost
  api := host + "mdocument/_doc/_search"
  sj, err := util.HttpPostJson(api, queryJson)
  if err==nil{
    count =  sj.GetPath("hits","total").MustInt()
    resultArray := sj.GetPath("hits", "hits").MustArray()
    for _, result := range resultArray {
      if eachMap, ok := result.(map[string]interface{}); ok {
        id, _ := strconv.Atoi(eachMap["_id"].(string))
        documentIds = append(documentIds, id)
      }
    }
  }
  return documentIds, count, err
}

关于sj.GetPath("hits","hits")原因如下:

es查询到多个结果的时候,返回结果如下:

{
    "took": 4,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
———>"hits": {
        "total": {
            "value": 2,
            "relation": "eq"
        },
        "max_score": 1.0,
———————>"hits": [ // 原始数据
            {
                "_index": "shopping",
                "_type": "_doc",
                "_id": "TYu9pn8BfWqG58AR7Mzw",
                "_score": 1.0,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://xxx.com/xm.jpg",
                    "price": 3999.00
                }
            },
            ...
        ]
    }
}

结果:

优化前:

优化后:

性能的具体提升使用ab自行进行压力测试

相关实践学习
使用阿里云Elasticsearch体验信息检索加速
通过创建登录阿里云Elasticsearch集群,使用DataWorks将MySQL数据同步至Elasticsearch,体验多条件检索效果,简单展示数据同步和信息检索加速的过程和操作。
ElasticSearch 入门精讲
ElasticSearch是一个开源的、基于Lucene的、分布式、高扩展、高实时的搜索与数据分析引擎。根据DB-Engines的排名显示,Elasticsearch是最受欢迎的企业搜索引擎,其次是Apache Solr(也是基于Lucene)。 ElasticSearch的实现原理主要分为以下几个步骤: 用户将数据提交到Elastic Search 数据库中 通过分词控制器去将对应的语句分词,将其权重和分词结果一并存入数据 当用户搜索数据时候,再根据权重将结果排名、打分 将返回结果呈现给用户 Elasticsearch可以用于搜索各种文档。它提供可扩展的搜索,具有接近实时的搜索,并支持多租户。
相关文章
|
2月前
|
JSON 运维 Go
Go 项目配置文件的定义和读取
Go 项目配置文件的定义和读取
|
15天前
|
自然语言处理 搜索推荐 数据库
高性能分布式搜索引擎Elasticsearch详解
高性能分布式搜索引擎Elasticsearch详解
47 4
高性能分布式搜索引擎Elasticsearch详解
|
7天前
|
网络协议 Java Maven
多模块项目使用ElasticSearch报错
多模块项目使用ElasticSearch报错
17 6
|
8天前
|
关系型数据库 Go 数据处理
高效数据迁移:使用Go语言优化ETL流程
在本文中,我们将探索Go语言在处理大规模数据迁移任务中的独特优势,以及如何通过Go语言的并发特性来优化数据提取、转换和加载(ETL)流程。不同于其他摘要,本文不仅展示了Go语言在ETL过程中的应用,还提供了实用的代码示例和性能对比分析。
|
22天前
|
JSON 自然语言处理 算法
ElasticSearch基础2——DSL查询文档,黑马旅游项目查询功能
DSL查询文档、RestClient查询文档、全文检索查询、精准查询、复合查询、地理坐标查询、分页、排序、高亮、黑马旅游案例
ElasticSearch基础2——DSL查询文档,黑马旅游项目查询功能
|
2月前
|
JSON 中间件 Go
go语言后端开发学习(四) —— 在go项目中使用Zap日志库
本文详细介绍了如何在Go项目中集成并配置Zap日志库。首先通过`go get -u go.uber.org/zap`命令安装Zap,接着展示了`Logger`与`Sugared Logger`两种日志记录器的基本用法。随后深入探讨了Zap的高级配置,包括如何将日志输出至文件、调整时间格式、记录调用者信息以及日志分割等。最后,文章演示了如何在gin框架中集成Zap,通过自定义中间件实现了日志记录和异常恢复功能。通过这些步骤,读者可以掌握Zap在实际项目中的应用与定制方法
go语言后端开发学习(四) —— 在go项目中使用Zap日志库
|
2月前
|
缓存 NoSQL Redis
go-zero微服务实战系列(七、请求量这么高该如何优化)
go-zero微服务实战系列(七、请求量这么高该如何优化)
|
2月前
|
API
企业项目迁移go-zero实战(二)
企业项目迁移go-zero实战(二)
|
2月前
|
Kubernetes 监控 Cloud Native
"解锁K8s新姿势!Cobra+Client-go强强联手,打造你的专属K8s监控神器,让资源优化与性能监控尽在掌握!"
【8月更文挑战第14天】在云原生领域,Kubernetes以出色的扩展性和定制化能力引领潮流。面对独特需求,自定义插件成为必要。本文通过Cobra与Client-go两大利器,打造一款监测特定标签Pods资源使用的K8s插件。Cobra简化CLI开发,Client-go则负责与K8s API交互。从初始化项目到实现查询逻辑,一步步引导你构建个性化工具,开启K8s集群智能化管理之旅。
39 2
|
2月前
|
JSON 缓存 监控
go语言后端开发学习(五)——如何在项目中使用Viper来配置环境
Viper 是一个强大的 Go 语言配置管理库,适用于各类应用,包括 Twelve-Factor Apps。相比仅支持 `.ini` 格式的 `go-ini`,Viper 支持更多配置格式如 JSON、TOML、YAML
go语言后端开发学习(五)——如何在项目中使用Viper来配置环境
下一篇
无影云桌面