Bläddra i källkod

fix:pdf研报使用es

zqbao 9 månader sedan
förälder
incheckning
eb15fa9775
6 ändrade filer med 335 tillägg och 4 borttagningar
  1. 59 2
      controllers/report_pdf.go
  2. 47 2
      models/report_pdf.go
  3. 169 0
      services/elastic/elastic.go
  4. 12 0
      services/elastic/elasticsearch.go
  5. 27 0
      utils/config.go
  6. 21 0
      utils/elastic.go

+ 59 - 2
controllers/report_pdf.go

@@ -6,9 +6,11 @@ import (
 	"eta/eta_mini_crm/models/request"
 	"eta/eta_mini_crm/models/response"
 	"eta/eta_mini_crm/services"
+	"eta/eta_mini_crm/services/elastic"
 	"eta/eta_mini_crm/utils"
 	"os"
 	"path"
+	"strconv"
 	"strings"
 	"time"
 
@@ -104,12 +106,24 @@ func (this *ReportPdfController) Add() {
 		SysRealName:        this.SysUser.SysRealName,
 		State:              utils.ReportStatusUp,
 	}
-	err = pdf.Add()
+	insertId, err := pdf.Insert()
 	if err != nil {
 		br.Msg = "添加失败"
 		br.ErrMsg = "pdf研报新增失败,Err:" + err.Error()
 		return
 	}
+	pdf.ReportPdfId = int(insertId)
+	// 添加es
+	go func(reportPdf *models.ReportPdf) {
+		reportpdfView := reportPdf.ToView()
+		docId := strconv.Itoa(reportpdfView.ReportPdfId)
+		err = elastic.EsAddOrEditReportPdf(utils.MINI_REPORT_INDEX_NAME, docId, reportpdfView)
+		if err != nil {
+			utils.FileLog.Info("pdf研报es新增失败,Err:" + err.Error())
+			return
+		}
+		utils.FileLog.Info("pdf研报es新增成功, pdfId:" + docId)
+	}(pdf)
 
 	br.Msg = "添加成功"
 	br.Ret = 200
@@ -425,6 +439,17 @@ func (this *ReportPdfController) Edit() {
 			br.ErrMsg = "文件更新失败,Err:" + err.Error()
 			return
 		}
+		// 编辑es
+		go func(reportPdf *models.ReportPdf) {
+			reportpdfView := reportPdf.ToView()
+			docId := strconv.Itoa(reportpdfView.ReportPdfId)
+			err = elastic.EsAddOrEditReportPdf(utils.MINI_REPORT_INDEX_NAME, docId, reportpdfView)
+			if err != nil {
+				utils.FileLog.Info("pdf研报es编辑失败,Err:" + err.Error())
+				return
+			}
+			utils.FileLog.Info("pdf研报es编辑成功, pdfId:" + docId)
+		}(reportPdf)
 	}
 	br.Msg = "研报编辑成功"
 	br.Ret = 200
@@ -466,6 +491,17 @@ func (this *ReportPdfController) Publish() {
 		br.ErrMsg = "发布研报失败,系统错误,Err:" + err.Error()
 		return
 	}
+	// 修改es
+	go func(reportPdf *models.ReportPdf) {
+		reportpdfView := reportPdf.ToView()
+		docId := strconv.Itoa(reportpdfView.ReportPdfId)
+		err = elastic.EsAddOrEditReportPdf(utils.MINI_REPORT_INDEX_NAME, docId, reportpdfView)
+		if err != nil {
+			utils.FileLog.Info("pdf研报es发布失败,Err:" + err.Error())
+			return
+		}
+		utils.FileLog.Info("pdf研报es发布成功, pdfId:" + docId)
+	}(reportPdf)
 	br.Msg = "发布研报成功"
 	br.Ret = 200
 	br.Success = true
@@ -505,6 +541,17 @@ func (this *ReportPdfController) PublishCancel() {
 		br.ErrMsg = "发布研报失败,系统错误,Err:" + err.Error()
 		return
 	}
+	// 修改es
+	go func(reportPdf *models.ReportPdf) {
+		reportpdfView := reportPdf.ToView()
+		docId := strconv.Itoa(reportpdfView.ReportPdfId)
+		err = elastic.EsAddOrEditReportPdf(utils.MINI_REPORT_INDEX_NAME, docId, reportpdfView)
+		if err != nil {
+			utils.FileLog.Info("pdf研报es取消发布失败,Err:" + err.Error())
+			return
+		}
+		utils.FileLog.Info("pdf研报es取消发布成功, pdfId:" + docId)
+	}(reportPdf)
 	br.Msg = "撤销研报成功"
 	br.Ret = 200
 	br.Success = true
@@ -545,7 +592,17 @@ func (this *ReportPdfController) Delete() {
 		br.ErrMsg = "研报删除失败,系统错误,Err:" + err.Error()
 		return
 	}
-
+	// 删除es
+	go func(reportPdf *models.ReportPdf) {
+		reportpdfView := reportPdf.ToView()
+		docId := strconv.Itoa(reportpdfView.ReportPdfId)
+		err = elastic.EsDeleteData(utils.MINI_REPORT_INDEX_NAME, docId)
+		if err != nil {
+			utils.FileLog.Info("pdf研报es删除失败,Err:" + err.Error())
+			return
+		}
+		utils.FileLog.Info("pdf研报es删除成功, pdfId:" + docId)
+	}(reportPdf)
 	br.Msg = "删除研报成功"
 	br.Ret = 200
 	br.Success = true

+ 47 - 2
models/report_pdf.go

@@ -1,6 +1,7 @@
 package models
 
 import (
+	"eta/eta_mini_crm/utils"
 	"time"
 
 	"github.com/beego/beego/v2/client/orm"
@@ -27,7 +28,28 @@ type ReportPdf struct {
 	State              int       `description:"状态"`
 }
 
-func (r *ReportPdf) Add() (err error) {
+type ReportPdfView struct {
+	ReportPdfId        int       `orm:"pk" description:"id"`
+	PdfUrl             string    `description:"pdf文件URL"`
+	PdfName            string    `description:"pdf文件名称"`
+	Title              string    `description:"pdf文件标题"`
+	Author             string    `description:"作者"`
+	Abstract           string    `description:"摘要"`
+	ClassifyIdFirst    int       `description:"一级分类id"`
+	ClassifyNameFirst  string    `description:"一级分类名称"`
+	ClassifyIdSecond   int       `description:"二级分类id"`
+	ClassifyNameSecond string    `description:"二级分类名称"`
+	Stage              int       `description:"期数"`
+	PublishTime        string    `description:"发布时间"`
+	ModifyTime         time.Time `description:"更新时间"`
+	Pv                 int       `description:"pv"`
+	Uv                 int       `description:"uv"`
+	SysUserId          int       `description:"创建人id"`
+	SysRealName        string    `description:"创建人姓名"`
+	State              int       `description:"状态"`
+}
+
+func (r *ReportPdf) Insert() (insertId int64, err error) {
 	o := orm.NewOrm()
 	// 计算研报期数
 	sql := `SELECT COUNT(*) + 1 AS count FROM report_pdf WHERE classify_id_second=?`
@@ -35,10 +57,33 @@ func (r *ReportPdf) Add() (err error) {
 	if err != nil {
 		return
 	}
-	_, err = o.Insert(r)
+	insertId, err = o.Insert(r)
 	return
 }
 
+func (r *ReportPdf) ToView() (item *ReportPdfView) {
+	item = new(ReportPdfView)
+	item.ReportPdfId = r.ReportPdfId
+	item.PdfUrl = r.PdfUrl
+	item.PdfName = r.PdfName
+	item.Title = r.Title
+	item.Author = r.Author
+	item.Abstract = r.Abstract
+	item.ClassifyIdFirst = r.ClassifyIdFirst
+	item.ClassifyNameFirst = r.ClassifyNameFirst
+	item.ClassifyIdSecond = r.ClassifyIdSecond
+	item.ClassifyNameSecond = r.ClassifyNameSecond
+	item.Stage = r.Stage
+	item.PublishTime = r.PublishTime.Format(utils.FormatDateTime)
+	item.ModifyTime = r.ModifyTime
+	item.Pv = r.Pv
+	item.Uv = r.Uv
+	item.SysUserId = r.SysUserId
+	item.SysRealName = r.SysRealName
+	return
+
+}
+
 func (r *ReportPdf) Update(cols []string) (err error) {
 	o := orm.NewOrm()
 	_, err = o.Update(r, cols...)

+ 169 - 0
services/elastic/elastic.go

@@ -0,0 +1,169 @@
+package elastic
+
+import (
+	"context"
+	"encoding/json"
+	"errors"
+	"eta/eta_mini_crm/models"
+	"eta/eta_mini_crm/utils"
+	"fmt"
+	"strconv"
+	"strings"
+
+	"github.com/olivere/elastic/v7"
+)
+
+// indexName:索引名称
+// mappingJson:表结构
+func EsCreateIndex(indexName, mappingJson string) (err error) {
+	client := utils.EsClient
+
+	//定义表结构
+	exists, err := client.IndexExists(indexName).Do(context.Background()) //<5>
+	if err != nil {
+		return
+	}
+	if !exists {
+		resp, err := client.CreateIndex(indexName).BodyJson(mappingJson).Do(context.Background())
+		//BodyJson(bodyJson).Do(context.Background())
+		if err != nil {
+			fmt.Println("CreateIndex Err:" + err.Error())
+			return err
+		}
+		fmt.Println(resp.Index, resp.ShardsAcknowledged, resp.Acknowledged)
+	} else {
+		fmt.Println(indexName + " 已存在")
+	}
+	return
+}
+
+// EsDeleteData 删除es中的指标数据
+func EsDeleteData(indexName, docId string) (err error) {
+	defer func() {
+		if err != nil {
+			fmt.Println("EsDeleteEdbInfoData Err:", err.Error())
+		}
+	}()
+	client := utils.EsClient
+
+	resp, err := client.Delete().Index(indexName).Id(docId).Do(context.Background())
+	fmt.Println(resp)
+	if err != nil {
+		return
+	}
+	if resp.Status == 0 {
+		fmt.Println("删除成功")
+	} else {
+		fmt.Println("AddData", resp.Status, resp.Result)
+	}
+	return
+}
+
+// EsAddOrEditReport 新增编辑es报告
+func EsAddOrEditReportPdf(indexName, docId string, item *models.ReportPdfView) (err error) {
+	defer func() {
+		if err != nil {
+			fmt.Println("EsAddOrEditReport Err:", err.Error())
+		}
+	}()
+	client := utils.EsClient
+
+	// docId为报告ID+章节ID
+	searchById, err := client.Get().Index(indexName).Id(docId).Do(context.Background())
+	if err != nil && !strings.Contains(err.Error(), "404") {
+		fmt.Println("Get Err" + err.Error())
+		return
+	}
+	if searchById != nil && searchById.Found {
+		resp, err := client.Update().Index(indexName).Id(docId).Doc(map[string]interface{}{
+			"ReportPdfId":        item.ReportPdfId,
+			"PdfUrl":             item.PdfUrl,
+			"PdfName":            item.PdfName,
+			"Title":              item.Title,
+			"Abstract":           item.Abstract,
+			"PublishTime":        item.PublishTime,
+			"ModifyTime":         item.ModifyTime,
+			"SysUserId":          item.SysUserId,
+			"SysRealName":        item.SysRealName,
+			"Author":             item.Author,
+			"State":              item.State,
+			"ClassifyIdFirst":    item.ClassifyIdFirst,
+			"ClassifyNameFirst":  item.ClassifyNameFirst,
+			"ClassifyIdSecond":   item.ClassifyIdSecond,
+			"ClassifyNameSecond": item.ClassifyNameSecond,
+			"Stage":              item.Stage,
+		}).Do(context.Background())
+		if err != nil {
+			return err
+		}
+		//fmt.Println(resp.Status, resp.Result)
+		if resp.Status == 0 {
+			fmt.Println("修改成功" + docId)
+			err = nil
+		} else {
+			fmt.Println("EditData", resp.Status, resp.Result)
+		}
+	} else {
+		resp, err := client.Index().Index(indexName).Id(docId).BodyJson(item).Do(context.Background())
+		if err != nil {
+			fmt.Println("新增失败:", err.Error())
+			return err
+		}
+		if resp.Status == 0 && resp.Result == "created" {
+			fmt.Println("新增成功" + docId)
+			return nil
+		} else {
+			fmt.Println("AddData", resp.Status, resp.Result)
+		}
+	}
+	return
+}
+
+// AnalyzeResp 分词接口返回结构体
+type AnalyzeResp struct {
+	Tokens []struct {
+		EndOffset   int64  `json:"end_offset"`
+		Position    int64  `json:"position"`
+		StartOffset int64  `json:"start_offset"`
+		Token       string `json:"token"`
+		Type        string `json:"type"`
+	} `json:"tokens"`
+}
+
+// Analyze 根据输入的文字获取分词后的文字
+func Analyze(content string) (contentList []string, err error) {
+	defer func() {
+		if err != nil {
+			fmt.Println("Analyze Err:", err.Error())
+		}
+	}()
+	client := utils.EsClient
+
+	queryMap := map[string]string{
+		"text":     content,
+		"analyzer": "ik_max_word",
+	}
+	res, err := client.PerformRequest(
+		context.Background(),
+		elastic.PerformRequestOptions{
+			Method: "GET",
+			Path:   "/_analyze",
+			Body:   queryMap,
+			Stream: false,
+		},
+	)
+	if res.StatusCode == 200 {
+		var analyzeResp AnalyzeResp
+		tmpErr := json.Unmarshal(res.Body, &analyzeResp)
+		if tmpErr != nil {
+			err = errors.New("返回数据转结构体失败:" + tmpErr.Error())
+			return
+		}
+		for _, v := range analyzeResp.Tokens {
+			contentList = append(contentList, v.Token)
+		}
+	} else {
+		err = errors.New("分词失败,返回code异常:" + strconv.Itoa(res.StatusCode))
+	}
+	return
+}

+ 12 - 0
services/elastic/elasticsearch.go

@@ -0,0 +1,12 @@
+package elastic
+
+import (
+	"fmt"
+)
+
+type tracelog struct{}
+
+// 实现输出
+func (tracelog) Printf(format string, v ...interface{}) {
+	fmt.Printf(format, v...)
+}

+ 27 - 0
utils/config.go

@@ -45,6 +45,18 @@ var (
 	RESOURCE_DIR string
 )
 
+// ES配置
+var (
+	ES_URL      string // ES服务器地址
+	ES_USERNAME string // ES账号
+	ES_PASSWORD string // ES密码
+)
+
+// ES索引配置
+var (
+	MINI_REPORT_INDEX_NAME string // 小程序的pdf报告索引
+)
+
 var (
 	LogPath    string //调用过程中的日志存放地址
 	LogFile    string
@@ -112,6 +124,21 @@ func init() {
 		STSTokenCacheKey = config["sts_token_cache_key"]
 	}
 
+	// ES配置
+	{
+		ES_URL = config["es_url"]
+		ES_USERNAME = config["es_username"]
+		ES_PASSWORD = config["es_password"]
+	}
+
+	// ES 索引
+	{
+		MINI_REPORT_INDEX_NAME = config["mini_report_index_name"]
+	}
+
+	// 初始化ES
+	initEs()
+
 	// 静态文件目录
 	STATIC_DIR = config["static_dir"]
 	if STATIC_DIR == "" {

+ 21 - 0
utils/elastic.go

@@ -0,0 +1,21 @@
+package utils
+
+import (
+	"github.com/olivere/elastic/v7"
+)
+
+// EsClient es客户端
+var EsClient *elastic.Client
+
+func initEs() {
+	client, err := elastic.NewClient(
+		elastic.SetURL(ES_URL),
+		elastic.SetBasicAuth(ES_USERNAME, ES_PASSWORD),
+		elastic.SetSniff(false))
+	EsClient = client
+	if err != nil {
+		panic("ElasticSearch连接失败,err:" + err.Error())
+		//go alarm_msg.SendAlarmMsg("ElasticSearch连接失败", 2)
+	}
+	return
+}