1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- package knowledge
- import (
- "context"
- "encoding/json"
- "eta_gn/eta_report/models"
- "eta_gn/eta_report/utils"
- "fmt"
- "html"
- "strconv"
- "strings"
- "github.com/PuerkitoBio/goquery"
- )
- // EsAddOrEditKnowledgeResource 新增/修改es中的知识资源数据
- func EsAddOrEditKnowledgeResource(item *models.KnowledgeResource) (err error) {
- defer func() {
- if err != nil {
- fmt.Println("EsAddOrEditData Err:", err.Error())
- utils.FileLog.Info("EsAddOrEditKnowledgeResource err:", err)
- }
- }()
- indexName := utils.EsKnowledgeResourceIndexName
- client := utils.EsClient
- if item.IsFile == 0 {
- content := ExtractTextFromResourceContent(item.Content)
- contentRunes := []rune(content)
- if len(contentRunes) > 60 {
- item.Content = string(contentRunes[:60])
- } else {
- item.Content = content
- }
- }
- request := client.Index().Index(indexName).Id(strconv.Itoa(item.KnowledgeResourceId)).BodyJson(item)
- response, err := request.Do(context.Background())
- if err != nil {
- jsonBytes, _ := json.Marshal(item)
- utils.FileLog.Info("add json:%s,EsAddOrEditKnowledgeResource err:%s", string(jsonBytes), err.Error())
- return
- }
- if response.Status == 0 {
- err = nil
- } else {
- fmt.Println("EsAddOrEditKnowledgeResource:", response.Status, response.Result)
- }
- return
- }
- func ExtractTextFromResourceContent(content string) (text string) {
- content = html.UnescapeString(content)
- doc, err := goquery.NewDocumentFromReader(strings.NewReader(content))
- if err != nil {
- return
- }
- text = doc.Text()
- text = strings.ReplaceAll(text, "\n", "")
- return
- }
- func UpdateEsKnowledgeResource(docId int, docFields map[string]interface{}) (err error) {
- defer func() {
- if err != nil {
- fmt.Println("EsAddOrEditData Err:", err.Error())
- utils.FileLog.Info("EsAddOrEditKnowledgeResource err:", err)
- }
- }()
- indexName := utils.EsKnowledgeResourceIndexName
- client := utils.EsClient
- res, err := client.Update().
- Index(indexName).
- Id(strconv.Itoa(docId)).
- Doc(docFields).
- Do(context.Background())
- if err != nil {
- utils.FileLog.Info("update docId:%d,UpdateEsKnowledgeResource err:%s", docId, err.Error())
- return
- }
- if res.Result == "updated" {
- err = nil
- } else {
- fmt.Println("UpdateEsKnowledgeResource:", res.Result)
- }
- return
- }
|