docService.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. package stdlib
  2. import (
  3. "app.yhyue.com/moapp/jy_docs/services/partner"
  4. "fmt"
  5. "log"
  6. "regexp"
  7. "strings"
  8. "time"
  9. "app.yhyue.com/moapp/jy_docs/rpc/stdlib/stdlib"
  10. "app.yhyue.com/moapp/jy_docs/services/model"
  11. jyDocsRpcUtil "app.yhyue.com/moapp/jy_docs/services/util"
  12. "app.yhyue.com/moapp/jybase/common"
  13. elastic "app.yhyue.com/moapp/jybase/esv7"
  14. )
  15. const (
  16. Es_Query_All = `{"query":{"match_all":{}}%s}`
  17. Es_Query_Boosting = `{"query":{"boosting":{"positive":{"bool":{"must":[%s]}},"negative":{"bool":{"must":[%s]}},"negative_boost":2}}%s}`
  18. Es_Query_Bool = `{"query":{"bool":{"filter":[%s]}}%s}`
  19. Es_Query_Append = `,"_source":["id","docName","price","downTimes","viewTimes","docSummary","uploadDate","docFileSize","docPageSize","docFileType","previewImgId","source","productType","docTags"],"from":%d,"size":%d`
  20. Es_Query_Highlight = `,"highlight":{"fields":{"docName":{},"docSummary":{"fragment_size":300,"number_of_fragments":1}}}`
  21. Es_Query_Sort = `,"sort":{%s}`
  22. Multi_Match = `{"multi_match":{"query":"%s","fields":["docName","docSummary^2"]}}`
  23. Multi_Match_Phrase = `{"multi_match":{"query":"%s","fields":["docName.docName_c","docSummary.docSummary_c"],"type":"phrase"}}`
  24. Terms = `{"terms":{"%s":[%s]}}`
  25. Term = `{"term":{"%s":%s}}`
  26. )
  27. var (
  28. Reg = regexp.MustCompile(`\s+`)
  29. )
  30. func FindDocumentById(id int) {
  31. log.Println(jyDocsRpcUtil.GetJyDocsDB().Exec("select * from ").Error)
  32. }
  33. func DocQuery(in *stdlib.DocQueryRequest, searchSource []string) *stdlib.DocQueryResponse {
  34. startNow := time.Now()
  35. defer common.Catch()
  36. in.KeyWord = strings.TrimSpace(in.KeyWord)
  37. musts := []string{}
  38. negative_musts := []string{}
  39. sorts := []string{}
  40. //搜索词
  41. if in.KeyWord != "" {
  42. sorts = append(sorts, `"_score":"desc"`)
  43. for _, v := range strings.Split(in.KeyWord, " ") {
  44. v = strings.ReplaceAll(v, `"`, `\"`)
  45. musts = append(musts, fmt.Sprintf(Multi_Match, v))
  46. negative_musts = append(negative_musts, fmt.Sprintf(Multi_Match_Phrase, v))
  47. }
  48. }
  49. for _, v := range in.Sort {
  50. if strings.HasPrefix(v, "-") {
  51. sorts = append(sorts, fmt.Sprintf(`"%s":"desc"`, strings.TrimLeft(v, "-")))
  52. } else {
  53. sorts = append(sorts, fmt.Sprintf(`"%s":"asc"`, v))
  54. }
  55. }
  56. //分类
  57. if len(in.DocClass) > 0 {
  58. musts = append(musts, fmt.Sprintf(Terms, "docClass", `"`+strings.Join(in.DocClass, `","`)+`"`))
  59. }
  60. //标签
  61. if len(in.DocTag) > 0 {
  62. musts = append(musts, fmt.Sprintf(Terms, "docTags", `"`+strings.Join(in.DocTag, `","`)+`"`))
  63. }
  64. // 文件类型
  65. if in.DocFileType > 0 {
  66. musts = append(musts, fmt.Sprintf(Term, "docFileType", `"`+fmt.Sprintf("%d", in.DocFileType)+`"`))
  67. }
  68. // 商品类型
  69. if in.ProductType > 0 {
  70. musts = append(musts, fmt.Sprintf(Term, "productType", `"`+fmt.Sprintf("%d", in.ProductType)+`"`))
  71. }
  72. query := ""
  73. query_sort := ""
  74. if len(sorts) > 0 {
  75. query_sort = fmt.Sprintf(Es_Query_Sort, strings.Join(sorts, ","))
  76. }
  77. query_append := fmt.Sprintf(Es_Query_Append, (in.PageNum-1)*in.PageSize, in.PageSize)
  78. if searchSource != nil && len(searchSource) > 0 {
  79. musts = append(musts, fmt.Sprintf(Terms, "source", strings.Join(searchSource, `,`)))
  80. }
  81. if len(musts) == 0 {
  82. query = fmt.Sprintf(Es_Query_All, fmt.Sprint(query_append, query_sort))
  83. } else if in.KeyWord != "" {
  84. query = fmt.Sprintf(Es_Query_Boosting, strings.Join(musts, ","), strings.Join(negative_musts, ","), fmt.Sprint(query_append, query_sort, Es_Query_Highlight))
  85. } else {
  86. query = fmt.Sprintf(Es_Query_Bool, strings.Join(musts, ","), fmt.Sprint(query_append, query_sort))
  87. }
  88. log.Println("query:", query)
  89. total, list := elastic.GetBySearchType(model.Es_JyDoc, "dfs_query_then_fetch", query)
  90. log.Println("es 查询耗时:", time.Since(startNow))
  91. step2 := time.Now()
  92. docs := []*stdlib.Doc{}
  93. //获取我购买的文档
  94. if list != nil {
  95. myDocs := map[string]int64{}
  96. if in.UserId != "" {
  97. docIds, whs := []interface{}{}, []string{}
  98. for _, v := range *list {
  99. whs = append(whs, "?")
  100. docIds = append(docIds, common.ObjToString(v["id"]))
  101. }
  102. args := []interface{}{in.UserId, model.UserDocStatus_Normal, in.AppId}
  103. args = append(args, docIds...)
  104. userDocs := []*model.UserDoc{}
  105. jyDocsRpcUtil.GetJyDocsDB().Exec(`select docId from user_doc where userId=? and isDelete=? and appId=? and isDownload=1 and docId in (`+strings.Join(whs, ",")+`)`, args...).Find(&userDocs)
  106. for _, v := range userDocs {
  107. myDocs[v.DocId] = 1
  108. }
  109. }
  110. for _, v := range *list {
  111. tags := strings.Split(common.ObjToString(v["docTags"]), ",")
  112. tmptags := []string{}
  113. subTag := ""
  114. //step3 := time.Now()
  115. for i := 0; i < len(tags); i++ {
  116. dtpKey := fmt.Sprintf("p_%s_0_class", tags[i]) //一级tag
  117. if _, ok := partner.DocClassMap[dtpKey]; ok && len(tmptags) == 0 {
  118. tmptags = append(tmptags, tags[i])
  119. } else {
  120. subTag = tags[i]
  121. }
  122. if subTag != "" && len(tmptags) > 0 {
  123. tmptags = append(tmptags, subTag)
  124. break
  125. }
  126. }
  127. //log.Println("step3", time.Since(step3))
  128. doc := &stdlib.Doc{
  129. DocId: common.ObjToString(v["id"]),
  130. DocName: common.ObjToString(v["docName"]),
  131. DocPageSize: common.Int64All(v["docPageSize"]),
  132. DocFileSize: common.Int64All(v["docFileSize"]),
  133. DownTimes: common.Int64All(v["downTimes"]),
  134. ViewTimes: common.Int64All(v["viewTimes"]),
  135. UploadDate: common.ObjToString(v["uploadDate"]),
  136. DocSummary: common.ObjToString(v["docSummary"]),
  137. DocFileType: model.DocFileType[common.IntAll(v["docFileType"])],
  138. PreviewImgId: common.InterfaceToStr(v["previewImgId"]),
  139. ProductType: common.Int64All(v["productType"]),
  140. Source: common.Int64All(v["source"]),
  141. DocTags: strings.Join(tmptags, " "),
  142. }
  143. highlight, _ := v["highlight"].(map[string][]string)
  144. if len(highlight["docName"]) > 0 {
  145. doc.DocName = highlight["docName"][0]
  146. }
  147. if len(highlight["docSummary"]) > 0 {
  148. doc.DocSummary = highlight["docSummary"][0]
  149. }
  150. doc.IsDownload = myDocs[doc.DocId]
  151. docs = append(docs, doc)
  152. }
  153. }
  154. log.Println("step2", time.Since(step2))
  155. log.Println("end", time.Since(startNow))
  156. return &stdlib.DocQueryResponse{
  157. Total: total,
  158. Docs: docs,
  159. Code: 1,
  160. }
  161. }