https://github.com/ttys3/gojieba-bleve/blob/master/bleve_test.go
import (
"fmt"
"github.com/yanyiwu/gojieba"
"os"
"strconv"
"strings"
"testing"
"time"
"github.com/blevesearch/bleve/v2"
"github.com/blevesearch/bleve/v2/analysis/analyzer/keyword"
)
var indexName string = "userIndex"
//创建索引
func TestCreate(t *testing.T) {
os.RemoveAll(indexName)
// open a new index
mapping := bleve.NewIndexMapping()
//userMapping := bleve.NewDocumentMapping()
//userMapping.AddFieldMappingsAt("Address", bleve.NewBooleanFieldMapping())
//mapping.DefaultMapping = userMapping
// Address的mapping映射,此字段不使用分词,只保存,用于term的绝对精确查询,类似 sql的 where = 条件查询
addressMapping := bleve.NewTextFieldMapping()
//不分词,只保存,需要使用keyword分词器,注意是 github.com/blevesearch/bleve/v2/analysis/analyzer/keyword, token下也有一个keyword,别引错了!!!!!
//addressMapping.Index = false
//addressMapping.SkipFreqNorm = true
addressMapping.DocValues = false
addressMapping.Analyzer = keyword.Name
//设置字段映射
mapping.DefaultMapping.AddFieldMappingsAt("Address", addressMapping)
_, err := bleve.New(indexName, mapping)
fmt.Println(err)
}
func TestGojieba(t *testing.T) {
str := "我是一个测试语句"
var words []string
use_hmm := true
x := gojieba.NewJieba()
defer x.Free()
words = x.CutForSearch(str, use_hmm)
fmt.Println(str)
fmt.Println("搜索引擎模式:", strings.Join(words, "/"))
index, _ := bleve.Open(indexName)
for i := 0; i < len(words); i++ {
jiebas := make(map[string]interface{})
jiebas["index"] = words[i]
jiebas["str"] = str
index.Index(strconv.FormatInt(time.Now().Unix(), 10), jiebas)
}
queryKey := bleve.NewQueryStringQuery("测试")
searchRequest := bleve.NewSearchRequest(queryKey)
//指定返回的字段
searchRequest.Fields = []string{"str"}
searchResult, _ := index.Search(searchRequest)
fmt.Println(searchResult)
}
=== RUN TestGojieba
我是一个测试语句
搜索引擎模式: 我/是/一个/测试/语句
1 matches, showing 1 through 1, took 380.064µs
1. 1620025502 (0.137229)
str
我是一个测试语句
--- PASS: TestGojieba (0.98s)
PASS
Process finished with exit code 0