search.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. package service
  2. import (
  3. MC "app.yhyue.com/moapp/jybase/common"
  4. "app.yhyue.com/moapp/jybase/encrypt"
  5. elastic "app.yhyue.com/moapp/jybase/es"
  6. "app.yhyue.com/moapp/jybase/redis"
  7. "bp.jydev.jianyu360.cn/BaseService/powerCheckCenter/rpc/pb"
  8. userPb "bp.jydev.jianyu360.cn/BaseService/userCenter/rpc/pb"
  9. "context"
  10. "fmt"
  11. "jyBXCore/rpc/entity"
  12. IC "jyBXCore/rpc/init"
  13. "jyBXCore/rpc/model/es"
  14. "jyBXCore/rpc/type/bxcore"
  15. "jyBXCore/rpc/util"
  16. "log"
  17. "strings"
  18. "time"
  19. )
  20. const (
  21. entQuery = `{"query":{"bool":{"must":[%s],"must_not":[%s]}},"_source":["_id","company_name","company_status","legal_person","capital","company_address","company_shortname","company_phone","establish_date"],"sort":[{"capital":{"order":"desc"}}]}`
  22. entQueryCount = `{"query":{"bool":{"must":[%s],"must_not":[%s]}}}`
  23. index, itype = "qyxy", "qyxy"
  24. query = `{%s "query":{"bool":{"must":[%s],"must_not": [{"term": {"buyer_name": ""}}]}}}`
  25. BuyerIndex = "buyer" // 采购单位index
  26. BuyerType = "buyer"
  27. )
  28. // GetBidSearchData 默认查询缓存数据 只查标题
  29. // 登录用户默认搜索500条数据,付费用户字段和免费用户字段不同,未登录用户查询5000条。
  30. // 标信息搜索 isCache:是否是获取缓存信息
  31. func GetBidSearchData(in *bxcore.SearchReq, isCache bool) (count int64, list []*bxcore.SearchList) {
  32. var start = int((in.PageNum - 1) * in.PageSize)
  33. if start >= 0 {
  34. t := time.Now()
  35. fields := MC.If(in.IsPay, es.BidSearchFieldOfVip, es.BidSearchFieldBase).(string)
  36. switch in.BidField {
  37. case "BIProperty": //物业专版-BI
  38. fields = es.BidSearchFieldProperty
  39. case "medical": //(医疗)领域化字段
  40. fields = es.BidSearchDomainField
  41. }
  42. //IC.C.FileSignBool列表是否显示附件开关
  43. if IC.C.FileSignBool {
  44. fields = fields + es.BidSearchFieldFile
  45. }
  46. biddingSearch := es.SearchByES{
  47. Index: MC.If(in.UserId == "", es.INDEXNoLogin, es.INDEX).(string),
  48. IType: MC.If(in.UserId == "", es.TYPENoLogin, es.TYPE).(string),
  49. Query: es.GetSearchQuery(in, es.GetBidSearchQuery(in)),
  50. //FindFields: MC.If(isCache, "title", "detail").(string),
  51. FindFields: in.SelectType,
  52. Order: es.BidSearchSort,
  53. Fields: fields,
  54. Start: MC.If(isCache, 0, start).(int),
  55. Limit: MC.If(isCache, MC.If(in.IsPay, IC.C.DefaultBidInfo.PayCount, IC.C.DefaultBidInfo.Count).(int), int(in.PageSize)).(int),
  56. Count: MC.If(strings.Contains(in.SelectType, "detail"), 115, 0).(int), //高亮正文数量
  57. HighLight: MC.If(strings.Contains(in.SelectType, "detail"), true, false).(bool) || MC.If(strings.Contains(in.SelectType, "filetext"), true, false).(bool), //是否高亮正文
  58. }
  59. var loginType int
  60. // 处理免费用户index
  61. if in.UserId == "" {
  62. loginType = es.LoginTypeNoLogin
  63. } else if !in.IsPay {
  64. biddingSearch.Index = IC.DB.EsFree.Index
  65. biddingSearch.IType = IC.DB.EsFree.Type
  66. loginType = es.LoginTypeFree
  67. } else {
  68. loginType = es.LoginTypePay
  69. }
  70. var repl *[]map[string]interface{}
  71. if in.UserId != "" {
  72. count, repl = biddingSearch.GetAllByNgramWithCount(loginType)
  73. } else {
  74. if IC.C.NoLoginSearch.Switch {
  75. if flag := IC.ReqLimitInit.Limit(context.Background()); flag == 1 {
  76. defer IC.ReqLimitInit.Release()
  77. } else {
  78. if flag == -2 {
  79. log.Println("等待队列已满")
  80. } else if flag == -1 {
  81. log.Println("等待超时")
  82. }
  83. return 0, nil
  84. }
  85. }
  86. count, repl = biddingSearch.GetAllByNgramWithCount(loginType)
  87. }
  88. if repl != nil && *repl != nil && len(*repl) > 0 {
  89. //格式化查询结果
  90. list = util.SearchListFormat(in.UserId, in.Industry, repl, strings.Contains(in.SelectType, "detail"))
  91. } else {
  92. log.Println("查询数据异常")
  93. }
  94. log.Println(in.KeyWords, "关键词 -1- 查询耗时:", time.Since(t).Seconds())
  95. }
  96. return
  97. }
  98. func EntSearch(searchCode string) ([]*bxcore.Search, int64) {
  99. data := make([]*bxcore.Search, 0, 0)
  100. count := int64(0)
  101. musts := make([]string, 0, 0)
  102. musts = append(musts, `{"range":{"company_type_int":{"to":"22"}}}`)
  103. thisQuery := []string{}
  104. //查询指定内容
  105. thisQuery = append(thisQuery, fmt.Sprintf(`{"match_phrase":{"name":"%s"}}`, searchCode))
  106. musts = append(musts, fmt.Sprintf(`{"bool":{"should":[%s],"minimum_should_match": 1}}`, strings.Join(thisQuery, ",")))
  107. sql := fmt.Sprintf(entQuery, strings.Join(musts, ","), "")
  108. sql = sql[:len(sql)-1] + fmt.Sprintf(`,"from":%d,"size":%d}`, 0, 5)
  109. log.Println("企业搜索sql:", sql)
  110. count, list := elastic.GetWithCount(index, itype, "", sql)
  111. if list != nil {
  112. for _, value := range *list {
  113. data = append(data, &bxcore.Search{
  114. Title: MC.InterfaceToStr(value["company_name"]),
  115. Url: encrypt.EncodeArticleId2ByCheck(MC.ObjToString(value["_id"])),
  116. })
  117. }
  118. }
  119. return data, count
  120. }
  121. func ProcureSearch(searchCode string) ([]*bxcore.Search, int64) {
  122. data := []*bxcore.Search{}
  123. count := int64(0)
  124. //数据查询处理
  125. entNameQuery := fmt.Sprintf(`{"multi_match": {"query": "%s","type": "phrase", "fields": ["name"]}}`, searchCode)
  126. qstr := fmt.Sprintf(query, fmt.Sprintf(`"from":%d,"size": %d,`, 0, 5), entNameQuery)
  127. log.Println("采购单位搜索sql:", qstr)
  128. count, rs := elastic.GetWithCount(BuyerIndex, BuyerType, "", qstr)
  129. //rs := elastic.Get(BuyerIndex, BuyerType, qstr) // 采购单位列表
  130. if rs == nil || len(*rs) == 0 {
  131. return data, count
  132. }
  133. for i := 0; i < len(*rs); i++ {
  134. data = append(data, &bxcore.Search{
  135. Title: MC.ObjToString((*rs)[i]["name"]),
  136. })
  137. }
  138. return data, count
  139. }
  140. // 菜单搜索
  141. func MenuSearch(in *bxcore.PolymerizeSearchReq) []*bxcore.MenuList {
  142. data := []*bxcore.MenuList{}
  143. workData := IC.Middleground.UserCenter.WorkDesktopMenuInfo(userPb.WorkDesktopMenuInfoReq{
  144. UserId: in.UserId,
  145. AppId: in.AppId,
  146. Platform: "PC",
  147. NewUserId: MC.InterfaceToStr(in.NewUserId),
  148. EntId: MC.InterfaceToStr(in.EntId),
  149. EntUserId: MC.InterfaceToStr(in.EntUserId),
  150. AccountId: MC.InterfaceToStr(in.AccountId),
  151. PositionType: MC.InterfaceToStr(in.PositionType),
  152. PositionId: MC.InterfaceToStr(in.PositionId),
  153. EntAccountId: MC.InterfaceToStr(in.EntAccountId),
  154. })
  155. if workData != nil && len(workData.Data.MenuList) > 0 {
  156. for _, value1 := range workData.Data.MenuList {
  157. for _, value2 := range value1.Child {
  158. for _, value3 := range value2.Child {
  159. if strings.Contains(value3.Name, in.SearchCode) {
  160. tipInfo := &bxcore.TipInfo{}
  161. if value3.TipInfo != nil {
  162. tipInfo = &bxcore.TipInfo{
  163. Title: value3.TipInfo.Title,
  164. Content: value3.TipInfo.Content,
  165. ConfirmUrl: value3.TipInfo.ConfirmUrl,
  166. ConfirmText: value3.TipInfo.ConfirmText,
  167. IsShowCancel: value3.TipInfo.IsShowCancel,
  168. AppType: value3.TipInfo.AppType,
  169. OpenType: value3.TipInfo.OpenType,
  170. }
  171. }
  172. data = append(data, &bxcore.MenuList{
  173. Name: value3.Name,
  174. Icon: value3.Icon,
  175. Url: value3.Url,
  176. Usable: value3.Usable,
  177. AppType: value3.AppType,
  178. OpenType: value3.OpenType,
  179. TipInfo: tipInfo,
  180. Match: value3.Match,
  181. Path: fmt.Sprintf("%s>%s>%s", value1.Name, value2.Name, value3.Name),
  182. })
  183. }
  184. }
  185. }
  186. }
  187. }
  188. return data
  189. }
  190. func SubscribeSearch(searchCode string, powerCheck *pb.CheckResp) []*bxcore.Search {
  191. data := []*bxcore.Search{}
  192. in := &bxcore.SearchReq{
  193. PageNum: int64(1),
  194. PageSize: int64(10),
  195. IsPay: false,
  196. SelectType: "title",
  197. KeyWords: searchCode,
  198. PublishTime: fmt.Sprintf("%v_%v", time.Now().AddDate(-1, 0, 0).Unix(), time.Now().Unix()),
  199. }
  200. isLimit := int64(0)
  201. isLimit = util.IsLimited(in.LimitFlag, in.UserId, powerCheck.Vip.Status > 0 || powerCheck.Member.Status > 0, in.IsNew)
  202. if isLimit == 1 { //没有被限制
  203. defer util.Limit()
  204. }
  205. list := []*bxcore.SearchList{}
  206. if isLimit == 1 {
  207. //付费用户搜索优化--默认搜索5年数据,数据量太多,接口反应太慢,前两页数据 时间范围根据配置缩小查询以达到快速查询的目的。
  208. t1 := time.Now()
  209. _, list = GetBidSearchData(in, false)
  210. log.Println("1查询耗时:", time.Since(t1))
  211. }
  212. if list != nil && len(list) > 0 {
  213. for _, value := range list {
  214. data = append(data, &bxcore.Search{
  215. Title: value.Title,
  216. Url: value.Id,
  217. DataTime: value.PublishTime,
  218. })
  219. }
  220. }
  221. return data
  222. }
  223. // IsOnTheWhitelist 是否在白名单
  224. func IsOnTheWhitelist(userId string) (flag bool, err error) {
  225. // mongoid 在白名单中没有查到 再去查职位id有没有在白名单里面
  226. flag, err = redis.Exists(entity.RedisPoly, fmt.Sprintf(entity.WhitelistRedisKey, userId))
  227. return
  228. }
  229. // FilterGeneric 通用词处理
  230. func FilterGeneric(keyWords string) string {
  231. keyWords = entity.FilterReg_3.ReplaceAllString(keyWords, "")
  232. keyWords = entity.FilterReg_2.ReplaceAllString(keyWords, "")
  233. keyWords = entity.FilterReg_1.ReplaceAllString(keyWords, "")
  234. keyWords = entity.FilterReg.ReplaceAllString(keyWords, "")
  235. return keyWords
  236. }
  237. // AdditionalFilterGeneric 附加词处理通用词
  238. // 逗号分割后再空格分割然后再过滤
  239. // 过滤完再合回去
  240. func AdditionalFilterGeneric(keyWords string) (additionalWords string) {
  241. keyWordsArr := strings.Split(keyWords, ",")
  242. var finalArr []string
  243. for i := 0; i < len(keyWordsArr); i++ {
  244. var tmpArr []string
  245. words := strings.Split(keyWordsArr[i], " ")
  246. for j := 0; j < len(words); j++ {
  247. word := FilterGeneric(words[j])
  248. if word != "" {
  249. tmpArr = append(tmpArr, word)
  250. }
  251. }
  252. if len(tmpArr) > 0 {
  253. // 还原空格分割
  254. spaceWord := strings.Join(tmpArr, " ")
  255. finalArr = append(finalArr, spaceWord)
  256. }
  257. }
  258. // 还原逗号分割
  259. if len(finalArr) > 0 {
  260. additionalWords = strings.Join(finalArr, ",")
  261. }
  262. return additionalWords
  263. }