rdluck 4 years ago
parent
commit
20b394c3c0
5 changed files with 195 additions and 22 deletions
  1. 42 0
      controllers/search.go
  2. 1 1
      models/home.go
  3. 5 0
      routers/router.go
  4. 141 19
      services/elasticsearch.go
  5. 6 2
      services/task.go

+ 42 - 0
controllers/search.go

@@ -0,0 +1,42 @@
+package controllers
+
+import (
+	"hongze/hongze_cygx/models"
+	"hongze/hongze_cygx/services"
+)
+
+type SearchController struct {
+	BaseCommonController
+}
+
+// @Title 搜索接口
+// @Description 搜索接口
+// @Param   KeyWord   query   string  true       "搜索关键词"
+// @Success 200 {object} models.HomeListResp
+// @router /list [get]
+func (this *SearchController) SearchList() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+	keyWord := this.GetString("KeyWord")
+	if keyWord == "" {
+		br.Msg = "请输入搜索词"
+		br.ErrMsg = "请输入搜索词"
+		return
+	}
+	pageSize := 20
+	result, err := services.SearchByKeyWord(keyWord, pageSize)
+	if err != nil {
+		br.Msg = "检索失败"
+		br.ErrMsg = "检索失败,Err:" + err.Error()
+		return
+	}
+	br.Ret = 200
+	br.Success = true
+	br.Msg = "获取成功"
+	br.Data = result
+}
+
+//https://blog.csdn.net/my_miuye/article/details/110496025

+ 1 - 1
models/home.go

@@ -33,4 +33,4 @@ func GetHomeList(condition string, pars []interface{}, startSize, pageSize int)
 type HomeListResp struct {
 	Paging *paging.PagingItem
 	List   []*HomeArticle
-}
+}

+ 5 - 0
routers/router.go

@@ -53,6 +53,11 @@ func init() {
 				&controllers.ConfigController{},
 			),
 		),
+		beego.NSNamespace("/search",
+			beego.NSInclude(
+				&controllers.SearchController{},
+			),
+		),
 	)
 	beego.AddNamespace(ns)
 }

+ 141 - 19
services/elasticsearch.go

@@ -1,22 +1,30 @@
 package services
 
 import (
-	"fmt"
 	"context"
-	"gopkg.in/olivere/elastic.v5"
-	"gopkg.in/olivere/elastic.v5/config"
-	//"hongze/hongze_cygx/models"
+	"fmt"
+	"hongze/hongze_cygx/models"
+	"hongze/hongze_cygx/utils"
+	"strconv"
+
+	//"gopkg.in/olivere/elastic.v5"
+	//"gopkg.in/olivere/elastic.v5/config"
+
+	"github.com/olivere/elastic/v7"
+	"github.com/olivere/elastic/v7/config"
 )
 
 const (
-	ES_URL      = "http://es-cn-oew21y5tl000i1wxm.public.elasticsearch.aliyuncs.com:9200"     //<1>
-	ES_USERNAME = "elastic"        //<2>
-	ES_PASSWORD = "hongze@2021"       //<3>
+	ES_URL      = "http://es-cn-nif227b580019rgw6.public.elasticsearch.aliyuncs.com:9200" //<1>
+	ES_USERNAME = "elastic"                                                               //<2>
+	ES_PASSWORD = "hongze@2021"                                                           //<3>
+	//Grafana pwd-> 20521bb9
+	//Grafana username-> emon
 )
 
-func SaveData()  {
-	fmt.Println("start")
-	var sniff = false    //<4>
+func SaveData() {
+	//fmt.Println("start")
+	var sniff = false //<4>
 	cfg := &config.Config{
 		URL:      ES_URL,
 		Username: ES_USERNAME,
@@ -26,24 +34,138 @@ func SaveData()  {
 	cfg.Sniff = &sniff
 	var client, err = elastic.NewClientFromConfig(cfg)
 	if err != nil {
-		fmt.Println("NewClientFromConfig Err:"+err.Error())
+		fmt.Println("NewClientFromConfig Err:" + err.Error())
 		return
 	}
 	var esIndex = "cygx_article"
-	exists, err := client.IndexExists(esIndex).Do(context.Background())   //<5>
+	//var esType = "article"
+	//
+	exists, err := client.IndexExists(esIndex).Do(context.Background()) //<5>
 	if err != nil {
-		fmt.Println("IndexExists Err:"+err.Error())
+		fmt.Println("IndexExists Err:" + err.Error())
 		return
 	}
 	if !exists {
-		_,err=client.CreateIndex(esIndex).Do(context.Background())
-		if err!=nil {
-			fmt.Println("CreateIndex Err:"+err.Error())
+		_, err = client.CreateIndex(esIndex).Do(context.Background())
+		if err != nil {
+			fmt.Println("CreateIndex Err:" + err.Error())
 			return
 		}
 	}
-	//item:=new(models.CygxArticle)
-	//item.Article_id
-	fmt.Println(exists)
+
+	//item, err := models.GetArticleDetailById(3138)
+	//if err != nil {
+	//	fmt.Println("GetArticleDetailById Err:" + err.Error())
+	//	return
+	//}
+	//
+	////插入一条数据,id指定为对应的name,若不指定则随机生成
+	//resp, err := client.Index().Index(esIndex).Id(strconv.Itoa(item.ArticleId)).BodyJson(item).Do(context.Background())
+	//if err != nil {
+	//	fmt.Println("insert es failed", err.Error())
+	//	return
+	//}
+	//fmt.Println(resp.Status)
+
+	/*
+
+		//根据id查询
+		searchById, err := client.Get().Index(esIndex).Type(esType).Id("3138").Do(context.Background())
+		if searchById.Found {
+			body, err := searchById.Source.MarshalJSON()
+			fmt.Println("body:",string(body))
+			fmt.Println(err)
+			//var resultType models.ArticleDetail
+			//if err := json.Unmarshal(searchById.Source,&resultType); err != nil{
+			//	log.Error(err.Error())
+			//}
+			//fmt.Printf("search by id: %#v \n",resultType)
+		}
+	*/
+
+	////查询index中所有的数据
+	//var resultType models.CygxArticle
+	//searchAll,err := client.Search(esIndex).Type(esType).Do(context.Background())
+	//for _,item := range searchAll.Each(reflect.TypeOf(resultType)) {
+	//	language := item.(models.CygxArticle)
+	//	fmt.Printf("search by index all: %#v \n",language)
+	//}
+
+	//根据检索条件查询
+
+	boolquery := elastic.NewBoolQuery()
+
+	boolquery.Should(elastic.NewMatchQuery("Body", "专家"))
+	highlight := elastic.NewHighlight()
+	highlight = highlight.Fields(elastic.NewHighlighterField("Body"))
+	highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
+
+	var pageSize int
+	pageSize = 20
+
+	searchByMatch, err := client.Search(esIndex).Highlight(highlight).Size(pageSize).Query(boolquery).Do(context.Background())
+
+	var result string
+	if searchByMatch.Hits != nil {
+
+	}
+	//fmt.Println(string(result))
+
+	utils.FileLog.Info("%s", string(result))
+
+	//var resultType models.CygxArticle
+	//for k,item := range searchByMatch.Each(reflect.TypeOf(resultType)) {
+	//	language := item.(models.CygxArticle)
+	//	fmt.Printf("search by match: %#v \n",language)
+	//
+	//	fmt.Println(k)
+	//	result,err:=json.Marshal(language)
+	//	fmt.Println(err)
+
+	//	utils.FileLog.Info("%s",string(result))
+	//}
+
+	// Perform the search request.
+	//searchByMatch, err := client.Search(esIndex).Type(esType).Query(query).From(1).Size(10).Do(context.Background())
+
 	fmt.Println("end")
 }
+
+func SearchByKeyWord(keyWord string, pageSize int) (result []*models.SearchItem, err error) {
+	if pageSize == 0 {
+		pageSize = 20
+	}
+	var sniff = false //<4>
+	cfg := &config.Config{
+		URL:      ES_URL,
+		Username: ES_USERNAME,
+		Password: ES_PASSWORD,
+	}
+
+	cfg.Sniff = &sniff
+	client, err := elastic.NewClientFromConfig(cfg)
+	if err != nil {
+		return
+	}
+	var esIndex = "cygx_article"
+	boolquery := elastic.NewBoolQuery()
+
+	boolquery.Should(elastic.NewMatchQuery("Body", keyWord))
+	highlight := elastic.NewHighlight()
+	highlight = highlight.Fields(elastic.NewHighlighterField("Body"))
+	highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
+
+	searchByMatch, err := client.Search(esIndex).Highlight(highlight).Size(pageSize).Query(boolquery).Do(context.Background())
+	if err != nil {
+		return
+	}
+	if searchByMatch.Hits != nil {
+		for _, v := range searchByMatch.Hits.Hits {
+			searchItem := new(models.SearchItem)
+			searchItem.ArticleId, _ = strconv.Atoi(v.Id)
+			searchItem.Body = v.Highlight["Body"]
+			result = append(result, searchItem)
+		}
+	}
+	return
+}

+ 6 - 2
services/task.go

@@ -1,9 +1,13 @@
 package services
 
-import "fmt"
+import (
+	"fmt"
+)
 
 func Task() {
 	fmt.Println("start")
-	//SaveData()
+	//keyWord := "专家"
+	//pageSize := 20
+	//SearchByKeyWord(keyWord, pageSize)
 	fmt.Println("end")
 }