Przeglądaj źródła

新增浏览历史记录

rdluck 4 lat temu
rodzic
commit
ddfe7f3c51

+ 30 - 10
controllers/article.go

@@ -2,12 +2,15 @@ package controllers
 
 import (
 	"encoding/json"
+	"fmt"
 	"hongze/hongze_cygx/models"
 	"hongze/hongze_cygx/utils"
 	"html"
 	"strconv"
 	"strings"
 	"time"
+
+	"github.com/astaxie/beego/cache"
 )
 
 type ArticleController struct {
@@ -92,16 +95,33 @@ func (this *ArticleController) Detail() {
 			}
 			if strings.Contains(companyPermission, articlePermission.PermissionName) {
 				hasPermission = 1
-				//新增浏览记录
-				record := new(models.CygxArticleViewRecord)
-				record.UserId = uid
-				record.ArticleId = articleId
-				record.CreateTime = time.Now()
-				record.Mobile = user.Mobile
-				record.Email = user.Email
-				record.CompanyId = user.CompanyId
-				record.CompanyName = user.CompanyName
-				go models.AddCygxArticleViewRecord(record)
+				bm, err := cache.NewCache("file", `{"CachePath":"./temp/cache","FileSuffix":".cache","DirectoryLevel":2,"EmbedExpiry":120}`)
+				if err != nil {
+					fmt.Println("false")
+				}
+				key := "ViewRecord:" + strconv.Itoa(uid) + "_" + strconv.Itoa(articleId)
+				if !bm.IsExist(key) {
+					//新增浏览记录
+					record := new(models.CygxArticleViewRecord)
+					record.UserId = uid
+					record.ArticleId = articleId
+					record.CreateTime = time.Now()
+					record.Mobile = user.Mobile
+					record.Email = user.Email
+					record.CompanyId = user.CompanyId
+					record.CompanyName = user.CompanyName
+					go models.AddCygxArticleViewRecord(record)
+					bm.Put(key, 1, 30*time.Second)
+				}
+				historyRecord := new(models.CygxArticleHistoryRecord)
+				historyRecord.UserId = uid
+				historyRecord.ArticleId = articleId
+				historyRecord.CreateTime = time.Now()
+				historyRecord.Mobile = user.Mobile
+				historyRecord.Email = user.Email
+				historyRecord.CompanyId = user.CompanyId
+				historyRecord.CompanyName = user.CompanyName
+				go models.AddCygxArticleHistoryRecord(historyRecord)
 			} else { //无该行业权限
 				hasPermission = 3
 			}

+ 3 - 1
controllers/search.go

@@ -48,7 +48,9 @@ func (this *SearchController) SearchList() {
 		categoryName := strings.Join(categoryNameArr, ",")
 	*/
 	indexName := "article"
-	result, err := services.EsQuery(indexName, keyWord)
+	result, err := services.EsMatchQuery(indexName, keyWord)
+	//indexName := "article_list"
+	//result, err := services.EsMatchPhraseQuery(indexName, keyWord)
 	if err != nil {
 		br.Msg = "检索失败"
 		br.ErrMsg = "检索失败,Err:" + err.Error()

+ 46 - 0
models/article_history_record.go

@@ -0,0 +1,46 @@
+package models
+
+import (
+	"hongze/hongze_cygx/utils"
+	"rdluck_tools/orm"
+	"time"
+)
+
+type CygxArticleHistoryRecord struct {
+	Id          int `orm:"column(id);pk"`
+	ArticleId   int
+	UserId      int
+	CreateTime  time.Time
+	Mobile      string    `description:"手机号"`
+	Email       string    `description:"邮箱"`
+	CompanyId   int       `description:"公司id"`
+	CompanyName string    `description:"公司名称"`
+	ModifyTime  time.Time `description:"修改时间"`
+}
+
+//添加历史信息
+func AddCygxArticleHistoryRecord(item *CygxArticleHistoryRecord) (lastId int64, err error) {
+	o := orm.NewOrm()
+	o.Begin()
+	defer func() {
+		if err == nil {
+			o.Commit()
+		} else {
+			o.Rollback()
+		}
+	}()
+	var count int
+	sql := `SELECT COUNT(1) AS count FROM cygx_article_history_record WHERE user_id=? AND article_id=? `
+	err = o.Raw(sql, item.UserId, item.ArticleId).QueryRow(&count)
+	if err != nil && err.Error() != utils.ErrNoRow() {
+		return
+	}
+	if count > 0 {
+		sql := `UPDATE cygx_article_history_record SET modify_time=NOW() WHERE user_id=? AND article_id=? `
+		_, err = o.Raw(sql, item.UserId, item.ArticleId).Exec()
+	} else {
+		item.ModifyTime = time.Now()
+		lastId, err = o.Insert(item)
+	}
+	return
+}

+ 1 - 0
models/db.go

@@ -39,5 +39,6 @@ func init() {
 		new(CygxApplyRecord),
 		new(CygxInterviewApply),
 		new(CygxArticle),
+		new(CygxArticleHistoryRecord),
 	)
 }

+ 3 - 3
models/user.go

@@ -181,15 +181,15 @@ type ArticleInterviewApplyListResp struct {
 }
 
 func GetArticleUserBrowseHistoryCount(userId int, endDate string) (count int, err error) {
-	sql := `SELECT COUNT(1) AS count FROM cygx_article_view_record AS a WHERE a.user_id=? AND a.create_time>=? `
+	sql := `SELECT COUNT(1) AS count FROM cygx_article_history_record AS a WHERE a.user_id=? AND a.create_time>=? `
 	err = orm.NewOrm().Raw(sql, userId, endDate).QueryRow(&count)
 	return
 }
 
 func GetArticleUserBrowseHistoryList(startSize, pageSize, userId int, endDate string) (items []*ArticleInterviewApplyList, err error) {
-	sql := `SELECT a.* FROM cygx_article_view_record AS a
+	sql := `SELECT a.* FROM cygx_article_history_record AS a
 			WHERE a.user_id=? AND a.create_time>=? 
-           ORDER BY a.create_time DESC LIMIT ?,? `
+           ORDER BY a.modify_time DESC LIMIT ?,? `
 	_, err = orm.NewOrm().Raw(sql, userId, endDate, startSize, pageSize).QueryRows(&items)
 	return
 }

+ 72 - 3
services/elastic.go

@@ -36,11 +36,15 @@ func EsCreateIndex(indexName, mappingJson string) (err error) {
 		return
 	}
 	if !exists {
-		_, err = client.CreateIndex(indexName).BodyJson(mappingJson).Do(context.Background())
+		resp, err := client.CreateIndex(indexName).BodyJson(mappingJson).Do(context.Background())
 		//BodyJson(bodyJson).Do(context.Background())
 		if err != nil {
-			return
+			fmt.Println("CreateIndex Err:"+err.Error())
+			return err
 		}
+		fmt.Println(resp.Index, resp.ShardsAcknowledged, resp.Acknowledged)
+	}else{
+		fmt.Println(indexName+" 已存在")
 	}
 	return
 }
@@ -92,7 +96,7 @@ func MappingModify(indexName, mappingJson string) {
 	return
 }
 
-func EsQuery(indexName, keyWord string) (result []*models.SearchItem, err error) {
+func EsMatchQuery(indexName, keyWord string) (result []*models.SearchItem, err error) {
 	client, err := NewClient()
 	pageSize := 20
 	keyWordArr, err := GetIndustryMapNameSliceV2(keyWord)
@@ -156,3 +160,68 @@ func EsQuery(indexName, keyWord string) (result []*models.SearchItem, err error)
 	}
 	return
 }
+
+func EsMatchPhraseQuery(indexName, keyWord string) (result []*models.SearchItem, err error) {
+	client, err := NewClient()
+	pageSize := 20
+	keyWordArr, err := GetIndustryMapNameSliceV2(keyWord)
+	fmt.Println(keyWordArr)
+	keyWordArr = RemoveDuplicatesAndEmpty(keyWordArr)
+	fmt.Println("-------------------------------")
+	fmt.Println(keyWordArr)
+	searchMap := make(map[int]int)
+	boolquery := elastic.NewBoolQuery()
+	//keyLen := len(keyWordArr)
+	//n := float64(keyLen)
+	matchArr := make([]elastic.Query, 0)
+	//matchq1 := elastic.NewMatchQuery("Title", keyWord).Boost(n + 1).Analyzer("ik_smart")
+	//matchq2 := elastic.NewMatchQuery("BodyText", keyWord).Boost(n + 1).Analyzer("ik_smart")
+	matchq1 := elastic.NewTermQuery("BodyText", keyWord)
+	matchArr = append(matchArr, matchq1)
+	//matchArr = append(matchArr, matchq2)
+	//for _, v := range keyWordArr {
+	//	if v != "" {
+	//		matchq1 := elastic.NewMatchQuery("Title", v).Boost(n).Analyzer("ik_smart")
+	//		matchq2 := elastic.NewMatchQuery("BodyText", v).Boost(n).Analyzer("ik_smart")
+	//		matchArr = append(matchArr, matchq1)
+	//		matchArr = append(matchArr, matchq2)
+	//	}
+	//	n--
+	//}
+	//boolquery.Should(matchArr...)
+	boolquery.Should(matchArr...)
+	highlight := elastic.NewHighlight()
+	highlight = highlight.Fields(elastic.NewHighlighterField("Title"), elastic.NewHighlighterField("BodyText"))
+	highlight = highlight.PreTags("<font color='red'>").PostTags("</font>")
+	request := client.Search(indexName).Highlight(highlight).Size(pageSize).Query(boolquery)
+	searchByMatch, err := request.Do(context.Background())
+	if searchByMatch.Hits != nil {
+		for _, v := range searchByMatch.Hits.Hits {
+			articleJson, err := v.Source.MarshalJSON()
+			if err != nil {
+				return nil, err
+			}
+			article := new(models.CygxArticle)
+			err = json.Unmarshal(articleJson, &article)
+			if err != nil {
+				return nil, err
+			}
+			if _, ok := searchMap[article.ArticleId]; !ok {
+				searchItem := new(models.SearchItem)
+				searchItem.ArticleId, _ = strconv.Atoi(v.Id)
+				searchItem.Body = v.Highlight["BodyText"]
+				var title string
+				if len(v.Highlight["Title"]) > 0 {
+					title = v.Highlight["Title"][0]
+				} else {
+					title = article.Title
+				}
+				searchItem.Title = title
+				searchItem.PublishDate = article.PublishDate
+				result = append(result, searchItem)
+				searchMap[article.ArticleId] = article.ArticleId
+			}
+		}
+	}
+	return
+}

+ 67 - 63
services/task.go

@@ -24,71 +24,75 @@ func Task() {
 	//修复报告内容
 	//GetArticleAll()
 
-	//
-	//	indexName:="article"
-	//	mappingJson := `{
-	//  "mappings": {
-	//    "dynamic": true,
-	//    "properties": {
-	//      "ArticleId": {
-	//        "type": "integer"
-	//      },
-	//      "Title": {
-	//        "type": "text",
-	//        "analyzer": "ik_smart"
-	//      },
-	//      "TitleEn": {
-	//        "type": "text",
-	//        "analyzer": "ik_smart"
-	//      },
-	//      "UpdateFrequency": {
-	//        "type": "text",
-	//        "analyzer": "ik_smart"
-	//      },
-	//      "CreateDate": {
-	//        "type": "text",
-	//        "analyzer": "ik_smart"
-	//      },
-	//      "PublishDate": {
-	//        "type": "text",
-	//        "analyzer": "ik_smart"
-	//      },
-	//      "Abstract": {
-	//        "type": "text",
-	//        "analyzer": "ik_smart"
-	//      },
-	//      "CategoryName": {
-	//        "type": "text",
-	//        "analyzer": "ik_smart"
-	//      },
-	//      "SubCategoryName": {
-	//        "type": "text",
-	//        "analyzer": "ik_smart"
-	//      },
-	//      "InterviewDate": {
-	//        "type": "text",
-	//        "analyzer": "ik_smart"
-	//      },
-	//      "ExpertBackground": {
-	//        "type": "text",
-	//        "analyzer": "ik_smart"
-	//      },
-	//      "ExpertNumber": {
-	//        "type": "text",
-	//        "analyzer": "ik_smart"
-	//      },
-	//      "Department": {
-	//        "type": "text",
-	//        "analyzer": "ik_smart"
-	//      },
-	//      "ArticleIdMd5": {
-	//        "type": "text",
-	//        "analyzer": "ik_smart"
-	//      }
+	//indexName := "article_list"
+	//		mappingJson := `{
+	//"mappings": {
+	//  "dynamic": true,
+	//  "properties": {
+	//    "ArticleId": {
+	//      "type": "integer"
+	//    },
+	//    "Title": {
+	//      "type": "text",
+	//      "analyzer": "ik_smart"
+	//    },
+	//    "TitleEn": {
+	//      "type": "text",
+	//      "analyzer": "ik_smart"
+	//    },
+	//    "UpdateFrequency": {
+	//      "type": "text",
+	//      "analyzer": "ik_smart"
+	//    },
+	//    "CreateDate": {
+	//      "type": "text",
+	//      "analyzer": "ik_smart"
+	//    },
+	//    "PublishDate": {
+	//      "type": "text",
+	//      "analyzer": "ik_smart"
+	//    },
+	//    "Abstract": {
+	//      "type": "text",
+	//      "analyzer": "ik_smart"
+	//    },
+	//    "CategoryName": {
+	//      "type": "text",
+	//      "analyzer": "ik_smart"
+	//    },
+	//    "SubCategoryName": {
+	//      "type": "text",
+	//      "analyzer": "ik_smart"
+	//    },
+	//    "InterviewDate": {
+	//      "type": "text",
+	//      "analyzer": "ik_smart"
+	//    },
+	//    "ExpertBackground": {
+	//      "type": "text",
+	//      "analyzer": "ik_smart"
+	//    },
+	//    "ExpertNumber": {
+	//      "type": "text",
+	//      "analyzer": "ik_smart"
+	//    },
+	//    "Department": {
+	//      "type": "text",
+	//      "analyzer": "ik_smart"
+	//    },
+	//    "BodyText": {
+	//      "type": "text",
+	//      "analyzer": "ik_smart"
+	//    },
+	//    "ArticleIdMd5": {
+	//      "type": "text",
+	//      "analyzer": "ik_smart"
 	//    }
 	//  }
+	//}
 	//}`
-	//	CreateIndex(indexName,mappingJson)
+	// EsCreateIndex(indexName,mappingJson)
+
 	//插入数据
 	//allList, err := models.GetArticleAll()
 	//if err != nil {
@@ -96,7 +100,7 @@ func Task() {
 	//	return
 	//}
 	//
-	//indexName := "article"
+	////indexName := "article"
 	//
 	//for _, v := range allList {
 	//	content := html.UnescapeString(v.Body)