知识分享之Golang——Bleve官方案例解析

知识分享之Golang——Bleve官方案例解析

背景

知识分享之Golang篇是我在日常使用Golang时学习到的各种各样的知识的记录,将其整理出来以文章的形式分享给大家,来进行共同学习。欢迎大家进行持续关注。

知识分享系列目前包含Java、Golang、Linux、Docker等等。

开发环境

  • 系统:windows10
  • 语言:Golang
  • 组件库:Bleve
  • golang版本:1.17
  • 组件官网:http://blevesearch.com/
  • 组件仓库:https://github.com/blevesearch/bleve
  • 开源协议:Apache-2.0 License

内容

官方案例解析:
1、声明索引并存储内容

// 声明存储的索引内容
message := struct{
    Id   string
    From string
    Body string
}{
    Id:   "example",
    From: "[email protected]",
    Body: "bleve indexing is easy",
}
// 创建一个默认索引结构
mapping := bleve.NewIndexMapping()
// 新建一个example.bleve目录用于存储该索引的所有信息,并返回索引对象
index, err := bleve.New("example.bleve", mapping)
if err != nil {
    panic(err)
}
// 添加一个简单的索引内容,由于使用了默认的分词引擎,因此这里会将message中的Body进行按照空格分词,在搜索时可以有效搜索出来
index.Index(message.Id, message)

2、根据索引查找内容

// 打开之前的索引
index, _ := bleve.Open("example.bleve")
// 声明一个查找对象,这里查找的内容是bleve
query := bleve.NewQueryStringQuery("bleve")
// 获取一个新的搜索对象
searchRequest := bleve.NewSearchRequest(query)
// 在索引中搜索对象是否存在
searchResult, _ := index.Search(searchRequest)

本文声明:

88x31.png

知识共享许可协议
本作品由 cn華少 采用 知识共享署名-非商业性使用 4.0 国际许可协议 进行许可。

你可能感兴趣的:(知识分享之Golang——Bleve官方案例解析)