utiltag.go 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967
  1. package util
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "log"
  8. "models"
  9. "mongodb"
  10. "qfw/util"
  11. // "qfw/util/elastic"
  12. esv "es"
  13. sql "sqlmodel"
  14. "strings"
  15. "sync"
  16. "time"
  17. es "github.com/olivere/elastic"
  18. "gopkg.in/mgo.v2/bson"
  19. )
  20. const (
  21. TitleMatchType = "1" //标题匹配
  22. DetailMatchType = "2" //全文匹配
  23. PurchasingMatchType = "3" //标的物匹配
  24. AttachmentsMatchType = "4" //附件匹配
  25. ProjectnameMatchType = "5" //项目名称匹配
  26. BuyerMatchType = "6" //采购单位匹配
  27. SWinnerMatchType = "7" //中标单位匹配
  28. BuyerMatchType1 = "8" //采购单位(正则)匹配
  29. SWinnerMatchType1 = "9" //中标单位(正则)匹配
  30. TitleMatchTypeStr = "title" //标题匹配
  31. DetailMatchTypeStr = "detail" //全文匹配
  32. PurchasingMatchTypeStr = "purchasing" //标的物匹配
  33. AttachmentsMatchTypeStr = "filetext" //附件匹配
  34. ProjectnameMatchTypeStr = "projectname.pname" //项目名称匹配
  35. BuyerMatchTypeStr = "buyer" //项目名称匹配
  36. BuyerRegexpMatchTypeStr = "buyer.mbuyer" //采购单位正则匹配
  37. SWinnerMatchTypeStr = "s_winner" //项目名称匹配
  38. SWinnerRegexpMatchTypeStr = "s_winner.mwinner" //中标单位正则匹配
  39. TitleMatchTypeField = "title" //标题匹配
  40. DetailMatchTypeField = "detail" //全文匹配
  41. PurchasingMatchTypeField = "purchasing" //标的物匹配
  42. AttachmentsMatchTypeField = "filetext" //附件匹配
  43. ProjectnameMatchTypeField = "projectname.pname" //项目名称匹配
  44. BuyerMatchTypeField = "buyer" //项目名称匹配
  45. SWinnerMatchTypeField = "s_winner" //项目名称匹配
  46. MultiMatchType = "phrase"
  47. Standard = 1 //1:标准字段包,
  48. Advanced = 2 //2:高级字段包
  49. Standardstr = "standard" //1:标准字段包
  50. Advancedstr = "advanced" //2:高级字段包
  51. Url = "https://www.jianyu360.com/article/content/%s.html"
  52. )
  53. func UtilEsSaveData(sdataid string, datas *[]map[string]interface{}) error {
  54. defer util.Catch()
  55. if !Mgo.Del("tagsdata", bson.M{"s_dataid": sdataid}) {
  56. return errors.New("mongo del err")
  57. }
  58. for _, v := range *datas {
  59. Mgo.Save("tagsdata", v)
  60. }
  61. // if Mgo.SaveBulk("tagsdata", *datas...) {
  62. // return nil
  63. // } else {
  64. // return errors.New("mongo save err")
  65. // }
  66. return nil
  67. }
  68. type MySource struct {
  69. Querys string
  70. }
  71. func (m *MySource) Source() (interface{}, error) {
  72. mp := make(map[string]interface{})
  73. json.Unmarshal([]byte(m.Querys), &mp)
  74. return mp["query"], nil
  75. }
  76. // 客户规则
  77. func UtilEsFind1(tags map[string]interface{}) (error, int64) {
  78. defer util.Catch()
  79. ch := make(chan bool, 20)
  80. wg := &sync.WaitGroup{}
  81. arrsync := &sync.RWMutex{}
  82. sdataid := util.ObjToString(tags["s_dataid"])
  83. esquery := util.ObjToString(tags["s_esquery"])
  84. if IsNewSql != 0 {
  85. esquery = util.ObjToString(tags["s_esquery_search"])
  86. }
  87. clearKey := util.ObjToString(tags["s_globalclearkey"])
  88. clearKeyMatch := util.ObjToString(tags["s_globalclearkeymatch"])
  89. if len(esquery) < 1 || len(sdataid) < 1 {
  90. return errors.New("s_esquery or s_dataid no found"), 0
  91. }
  92. i_maxnum := util.Int64All(tags["i_maxnum"])
  93. if i_maxnum <= 0 {
  94. i_maxnum = 100
  95. }
  96. //
  97. maths := make([]map[string]string, 0)
  98. if orules, ok := tags["o_rules"].([]interface{}); ok {
  99. for _, v := range orules {
  100. orule, _ := v.(map[string]interface{})
  101. maths = append(maths, map[string]string{
  102. "s_matchkey": util.ObjToString(orule["s_matchkey"]),
  103. "s_keymatch": util.ObjToString(orule["s_keymatch"]),
  104. })
  105. }
  106. } else if orules, ok := tags["o_rules"].([]map[string]interface{}); ok {
  107. for _, v := range orules {
  108. maths = append(maths, map[string]string{
  109. "s_matchkey": util.ObjToString(v["s_matchkey"]),
  110. "s_keymatch": util.ObjToString(v["s_keymatch"]),
  111. })
  112. }
  113. } else {
  114. return errors.New("o_rules no found"), 0
  115. }
  116. ctx, _ := context.WithTimeout(context.Background(), 5*time.Minute)
  117. esCon := esv.VarEs.(*esv.EsV7)
  118. client := esCon.GetEsConn()
  119. defer esCon.DestoryEsConn(client)
  120. // esquery = esquery[:len(esquery)-1] + `,"size":` + fmt.Sprintf("%d", i_maxnum) + `}`
  121. cc := &MySource{
  122. Querys: esquery,
  123. }
  124. searchResult, err := client.Search(EsIndex).Query(cc).Size(int(i_maxnum)).Do(ctx)
  125. if err == nil && searchResult.Hits != nil {
  126. datas := make([]map[string]interface{}, 0)
  127. util.Debug("es查询到的数量:", searchResult.Hits.TotalHits.Value)
  128. util.Debug("es查询到的数量(实际):", len(searchResult.Hits.Hits))
  129. for _, v := range searchResult.Hits.Hits {
  130. wg.Add(1)
  131. ch <- true
  132. go func(tmpHit *es.SearchHit) {
  133. defer func() {
  134. <-ch
  135. arrsync.Unlock()
  136. wg.Done()
  137. }()
  138. arrsync.Lock()
  139. item := make(map[string]interface{})
  140. if json.Unmarshal(tmpHit.Source, &item) == nil {
  141. item["appid"] = tags["appid"]
  142. item["rulename"] = tags["s_name"]
  143. info_id := util.ObjToString(item["id"])
  144. item["info_id"] = info_id
  145. item["s_dataid"] = sdataid
  146. // item["s_jyhref"] = fmt.Sprintf(Url, util.CommonEncodeArticle("content", info_id))
  147. //
  148. subType := util.ObjToString(item["subtype"])
  149. subTypeStr := "拟建,采购意向,预告,预审,预审结果,论证意见,需求公示"
  150. if strings.Contains(subTypeStr, subType) {
  151. item["s_jyhref"] = `https://www.jianyu360.cn/article/bdprivate/` + util.CommonEncodeArticle("bdprivate", info_id) + `.html`
  152. } else {
  153. // item["s_jyhref"] = `https://www.jianyu360.cn/article/content/` + qu.CommonEncodeArticle("content", info_id) + `.html`
  154. item["s_jyhref"] = `https://www.jianyu360.cn/article/entservice/` + util.SE3.EncodeString(info_id) + `.html?appid`
  155. }
  156. //
  157. item["i_createtime"] = time.Now().Unix()
  158. delete(item, "_id")
  159. //清理词清空
  160. for _, v := range strings.Split(clearKey, ",") {
  161. ClearKeys(clearKeyMatch, v, item)
  162. }
  163. //二次匹配关键词
  164. matchKeys := GetMactchKey(maths, item)
  165. if len(maths) > 0 {
  166. if matchKeys != "" {
  167. item["s_matchkey"] = matchKeys
  168. }
  169. }
  170. findwinner := strings.TrimSpace(util.ObjToString(item["winner"]))
  171. if findwinner != "" {
  172. finddata := MgoEnps.FindOne(EnpsColl, bson.M{"company_name": findwinner})
  173. if finddata != nil {
  174. if legal_person := util.ObjToString(finddata["legal_person"]); legal_person != "" {
  175. item["legal_person"] = legal_person
  176. }
  177. if email := util.ObjToString(finddata["company_email"]); email != "" {
  178. item["company_email"] = email
  179. }
  180. if phone := util.ObjToString(finddata["company_phone"]); phone != "" {
  181. item["company_phone"] = phone
  182. }
  183. item["qyk"] = finddata
  184. if company_area := util.ObjToString(finddata["company_area"]); company_area != "" {
  185. item["company_area"] = company_area
  186. }
  187. if company_city := util.ObjToString(finddata["company_city"]); company_city != "" {
  188. item["company_city"] = company_city
  189. }
  190. if company_district := util.ObjToString(finddata["company_district"]); company_district != "" {
  191. item["company_district"] = company_district
  192. }
  193. //中标单位的社会征信代码
  194. if credit_no := util.ObjToString(finddata["credit_no"]); credit_no != "" {
  195. item["winner_credit_no"] = credit_no
  196. }
  197. }
  198. }
  199. agency := strings.TrimSpace(util.ObjToString(item["agency"]))
  200. if agency != "" {
  201. finddata := MgoEnps.FindOne(EnpsColl, bson.M{"company_name": agency})
  202. if finddata != nil {
  203. //社会征信代码
  204. if credit_no := util.ObjToString(finddata["credit_no"]); credit_no != "" {
  205. item["agency_credit_no"] = credit_no
  206. }
  207. }
  208. }
  209. buyer := strings.TrimSpace(util.ObjToString(item["buyer"]))
  210. if buyer != "" {
  211. finddata := MgoBuyer.FindOne(BuyerEntColl, bson.M{"company_name": buyer})
  212. if finddata != nil {
  213. //社会征信代码
  214. if credit_no := util.ObjToString(finddata["credit_no"]); credit_no != "" {
  215. item["buyer_credit_no"] = credit_no
  216. }
  217. }
  218. }
  219. //匹配公告附件
  220. info := MgoBidding.FindOne("bidding", bson.M{"_id": mongodb.StringTOBsonId(info_id)})
  221. if info != nil {
  222. log.Println("id", item["info_id"])
  223. if info["projectinfo"] != nil {
  224. projectInfo := util.ObjToMap(info["projectinfo"])
  225. if projectInfo != nil && len(*projectInfo) > 0 {
  226. if (*projectInfo)["attachments"] != nil {
  227. filesArr := []map[string]interface{}{}
  228. fileUrl := util.ObjToString(Sysconfig["file_downloadurl"])
  229. if attachments, oks := (*projectInfo)["attachments"].(map[string]interface{}); oks {
  230. for _, v := range attachments {
  231. if atta, ok := v.(map[string]interface{}); ok {
  232. if atta["fid"] != nil && util.ObjToString(atta["fid"]) != "" {
  233. fileMap := map[string]interface{}{
  234. "filename": atta["filename"],
  235. "url": fileUrl + util.ObjToString(atta["fid"]),
  236. }
  237. filesArr = append(filesArr, fileMap)
  238. } else {
  239. if atta["org_url"] != nil {
  240. fileMap := map[string]interface{}{
  241. "filename": atta["filename"],
  242. "url": util.ObjToString(atta["org_url"]),
  243. }
  244. filesArr = append(filesArr, fileMap)
  245. }
  246. }
  247. }
  248. }
  249. }
  250. log.Println("查询附件结果:", info_id, "附件数量:", len(filesArr))
  251. if len(filesArr) > 0 {
  252. item["filehref"] = filesArr
  253. }
  254. }
  255. }
  256. }
  257. } else {
  258. log.Println("id", item["info_id"], "bidding为空")
  259. }
  260. //项目id
  261. projectId := GetProjectId(info_id)
  262. if projectId != "" {
  263. item["projectId"] = SE2.EncodeString(projectId)
  264. }
  265. datas = append(datas, item)
  266. } else {
  267. log.Println("id", item["_id"], "信息为空")
  268. }
  269. }(v)
  270. }
  271. wg.Wait()
  272. count := Es.Count(EsIndex, EsType, esquery)
  273. Mgo.Update("entniche_rule", bson.M{"_id": tags["_id"]}, bson.M{
  274. "$set": bson.M{
  275. "i_estotal": count,
  276. }}, false, false)
  277. return UtilEsSaveData(sdataid, &datas), count
  278. } else {
  279. util.Debug(err)
  280. return err, 0
  281. }
  282. }
  283. func ClearKeys(types, key string, data map[string]interface{}) {
  284. if strings.Contains(types, "1") {
  285. title := util.ObjToString(data["title"])
  286. data["title"] = strings.ReplaceAll(title, key, "")
  287. }
  288. if strings.Contains(types, "2") {
  289. detail := util.ObjToString(data["detail"])
  290. data["detail"] = strings.ReplaceAll(detail, key, "")
  291. }
  292. if strings.Contains(types, "3") {
  293. purchasing := util.ObjToString(data["purchasing"])
  294. data["purchasing"] = strings.ReplaceAll(purchasing, key, "")
  295. }
  296. if strings.Contains(types, "4") {
  297. filetext := util.ObjToString(data["filetext"])
  298. data["filetext"] = strings.ReplaceAll(filetext, key, "")
  299. }
  300. if strings.Contains(types, "5") {
  301. projectname := util.ObjToString(data["projectname"])
  302. data["projectname"] = strings.ReplaceAll(projectname, key, "")
  303. }
  304. if strings.Contains(types, "6") || strings.Contains(types, "8") {
  305. buyer := util.ObjToString(data["buyer"])
  306. data["buyer"] = strings.ReplaceAll(buyer, key, "")
  307. }
  308. if strings.Contains(types, "7") || strings.Contains(types, "9") {
  309. winner := util.ObjToString(data["s_winner"])
  310. data["s_winner"] = strings.ReplaceAll(winner, key, "")
  311. }
  312. }
  313. func GetTimeInterval(startTime, entTime time.Time, n int) []map[string]interface{} {
  314. timeList := []map[string]interface{}{}
  315. endTimeTmp := startTime
  316. for endTimeTmp.Unix() < entTime.Unix() {
  317. var endTime_ time.Time
  318. startTime = endTimeTmp
  319. endTimeTmp = startTime.AddDate(0, n, 0)
  320. if endTimeTmp.Unix() > entTime.Unix() {
  321. endTime_ = entTime
  322. timeList = append(timeList, map[string]interface{}{"startTime": startTime.Unix(), "endTime": endTime_.Unix()})
  323. break
  324. } else {
  325. endTime_ = endTimeTmp
  326. timeList = append(timeList, map[string]interface{}{"startTime": startTime.Unix(), "endTime": endTime_.Unix()})
  327. }
  328. }
  329. //log.Println(timeList)
  330. return timeList
  331. }
  332. func Utiltags(tag map[string]interface{}) string {
  333. defer util.Catch()
  334. tmpbyte, _ := json.Marshal(tag)
  335. tab := models.Tag{}
  336. err := json.Unmarshal(tmpbyte, &tab)
  337. if err != nil {
  338. return "json err:" + err.Error()
  339. }
  340. //log.Println("前端数据", tab)
  341. QueryObjecct := sql.QueryObjecct{}
  342. ffBoolObject := sql.BoolObject{}
  343. adsBoolObect := sql.NewEsObject{}
  344. if tab.Sarea != "" {
  345. adsBoolObect.Bool.Should = append(adsBoolObect.Bool.Should, sql.AreaCityDistrictMust{AreaCityDistrict: &sql.AreaCityDistrict{Area: strings.Split(tab.Sarea, ",")}})
  346. }
  347. if tab.Scity != "" {
  348. adsBoolObect.Bool.Should = append(adsBoolObect.Bool.Should, sql.AreaCityDistrictMust{AreaCityDistrict: &sql.AreaCityDistrict{City: strings.Split(tab.Scity, ",")}})
  349. }
  350. if tab.Sdistrict != "" {
  351. //城市——区县
  352. cityds := strings.Split(tab.Sdistrict, ",")
  353. var ds []string
  354. for _, v := range cityds {
  355. ds = append(ds, strings.Split(v, "-")[1])
  356. }
  357. adsBoolObect.Bool.Should = append(adsBoolObect.Bool.Should, sql.AreaCityDistrictMust{AreaCityDistrict: &sql.AreaCityDistrict{District: ds}})
  358. }
  359. if len(adsBoolObect.Bool.Should) > 0 {
  360. ffBoolObject.Must = append(ffBoolObject.Must, adsBoolObect)
  361. }
  362. if tab.Stoptype != "" || tab.Ssubtype != "" {
  363. if len(tab.Stoptype) > 0 {
  364. toptypeSubtype := sql.ToptypeSubtype{}
  365. toptypeSubtype.Toptype = strings.Split(tab.Stoptype, ",")
  366. ffBoolObject.Must = append(ffBoolObject.Must, sql.ToptypeSubtypeMust{&toptypeSubtype})
  367. }
  368. if len(tab.Ssubtype) > 0 {
  369. toptypeSubtype := sql.ToptypeSubtype{}
  370. toptypeSubtype.Subtype = strings.Split(tab.Ssubtype, ",")
  371. ffBoolObject.Must = append(ffBoolObject.Must, sql.ToptypeSubtypeMust{&toptypeSubtype})
  372. }
  373. }
  374. if tab.Istarttime > 0 && tab.Iendtime > 0 {
  375. ffBoolObject.Must = append(ffBoolObject.Must, sql.PublishtimeMust{PublishtimeObject: &sql.PublishtimeObject{Publishtime: &sql.Publishtime{
  376. Gte: tab.Istarttime,
  377. Lt: tab.Iendtime,
  378. }}})
  379. } else if tab.Istarttime > 0 {
  380. ffBoolObject.Must = append(ffBoolObject.Must, sql.PublishtimeMust{PublishtimeObject: &sql.PublishtimeObject{Publishtime1: &sql.Publishtime1{
  381. Gte: tab.Istarttime,
  382. }}})
  383. } else if tab.Iendtime > 0 {
  384. ffBoolObject.Must = append(ffBoolObject.Must, sql.PublishtimeMust{PublishtimeObject: &sql.PublishtimeObject{Publishtime2: &sql.Publishtime2{
  385. Lt: tab.Iendtime,
  386. }}})
  387. }
  388. if tab.Sglobalbuyerclass != "" {
  389. if len(tab.Sglobalbuyerclass) > 0 {
  390. buyerclass := sql.BuyerclassObject{
  391. Terms: struct {
  392. Buyerclass []string `json:"buyerclass,omitempty"`
  393. }{
  394. Buyerclass: strings.Split(tab.Sglobalbuyerclass, ","),
  395. },
  396. }
  397. ffBoolObject.Must = append(ffBoolObject.Must, buyerclass)
  398. }
  399. }
  400. if tab.Sglobaltopscopeclass != "" || tab.Sglobalsubscopeclass != "" {
  401. if len(tab.Sglobaltopscopeclass) > 0 {
  402. topScopeclass := sql.Scopeclass{}
  403. topScopeclass.Globaltopscopeclass = strings.Split(tab.Sglobaltopscopeclass, ",")
  404. ffBoolObject.Must = append(ffBoolObject.Must, sql.ScopeclassMust{&topScopeclass})
  405. } else if len(tab.Sglobalsubscopeclass) > 0 {
  406. subScopeclass := sql.Scopeclass{}
  407. subScopeclass.Globalsubscopeclass = strings.Split(tab.Sglobalsubscopeclass, ",")
  408. ffBoolObject.Must = append(ffBoolObject.Must, sql.ScopeclassMust{&subScopeclass})
  409. }
  410. }
  411. fqBoolObject := sql.BoolObject{}
  412. if len(tab.Sexistfields) > 0 {
  413. tmpsfields := strings.Split(tab.Sexistfields, ",")
  414. for _, v := range tmpsfields {
  415. fqBoolObject.MustNot = append(fqBoolObject.MustNot, sql.ExistfieldsObjectMust{
  416. ExistfieldsObject: &sql.ExistfieldsObject{Filter: struct {
  417. Missing struct {
  418. Field string `json:"field,omitempty"`
  419. } `json:"missing,omitempty"`
  420. }{
  421. Missing: struct {
  422. Field string `json:"field,omitempty"`
  423. }{Field: v},
  424. },
  425. },
  426. })
  427. }
  428. }
  429. newEsObject := sql.NewEsObject{}
  430. if tab.Sglobaladdkey != "" && tab.Sglobaladdkeymatch != "" {
  431. if tmps := strsToArr(tab.Sglobaladdkeymatch, "str"); tmps != nil {
  432. newEsObject = method1(newEsObject, tab.Sglobaladdkey, tab.Sglobaladdkeymatch, tmps)
  433. }
  434. }
  435. if len(newEsObject.Bool.Should) > 0 || len(newEsObject.Bool.MustNot) > 0 || len(newEsObject.Bool.Must) > 0 {
  436. fqBoolObject.Must = append(fqBoolObject.Must, newEsObject)
  437. }
  438. nots := sql.NewEsObject{}
  439. if tab.Sglobalnotkey != "" && tab.Sglobalnotkeymatch != "" {
  440. if tmps := strsToArr(tab.Sglobalnotkeymatch, "str"); tmps != nil {
  441. nots = method1(nots, tab.Sglobalnotkey, tab.Sglobalnotkeymatch, tmps)
  442. }
  443. }
  444. if len(nots.Bool.Should) > 0 {
  445. fqBoolObject.MustNot = append(fqBoolObject.MustNot, nots)
  446. }
  447. torules := sql.BoolObject{}
  448. for _, v := range tab.Orules {
  449. tmpses := sql.NewEsObject{}
  450. if skeymatchs := strsToArr(v.Skeymatch, "str"); skeymatchs != nil {
  451. tmpnewEsObject := sql.NewEsObject{}
  452. tmpnewEsObject = method1(tmpnewEsObject, v.Smatchkey, v.Skeymatch, skeymatchs)
  453. if len(tmpnewEsObject.Bool.Should) > 0 || len(tmpnewEsObject.Bool.Must) > 0 || len(tmpnewEsObject.Bool.MustNot) > 0 {
  454. tmpses.Bool.Must = append(tmpses.Bool.Must, tmpnewEsObject)
  455. }
  456. }
  457. if saddkeymatchs := strsToArr(v.Saddkeymatch, "str"); saddkeymatchs != nil {
  458. addkeyarr := sql.NewEsObject{}
  459. addkeyarr = method1(addkeyarr, v.Saddkey, v.Saddkeymatch, saddkeymatchs)
  460. if len(addkeyarr.Bool.Should) > 0 {
  461. tmpses.Bool.Must = append(tmpses.Bool.Must, addkeyarr)
  462. }
  463. }
  464. if snotkeymatchs := strsToArr(v.Snotkeymatch, "str"); snotkeymatchs != nil {
  465. tmpses = method2(tmpses, v.Snotkey, v.Snotkeymatch, snotkeymatchs)
  466. }
  467. if len(v.Stopscopeclass) > 0 {
  468. sArr := strings.Split(v.Stopscopeclass, ",")
  469. tmpses.Bool.Must = append(tmpses.Bool.Must, sql.TopscopeclassObject{
  470. Terms: struct {
  471. Topscopeclass []string `json:"s_topscopeclass,omitempty"`
  472. }{
  473. Topscopeclass: sArr,
  474. },
  475. })
  476. } else if len(v.Ssubscopeclass) > 0 {
  477. tmpses.Bool.Must = append(tmpses.Bool.Must, sql.SubscopeclassObject{
  478. Terms: struct {
  479. Subscopeclass []string `json:"s_subscopeclass,omitempty"`
  480. }{
  481. Subscopeclass: strings.Split(v.Ssubscopeclass, ","),
  482. },
  483. })
  484. }
  485. if len(v.Sbuyerclass) > 0 {
  486. tmpses.Bool.Must = append(tmpses.Bool.Must, sql.BuyerclassObject{
  487. Terms: struct {
  488. Buyerclass []string `json:"buyerclass,omitempty"`
  489. }{
  490. Buyerclass: strings.Split(v.Sbuyerclass, ","),
  491. },
  492. })
  493. }
  494. torules.Should = append(torules.Should, tmpses)
  495. }
  496. bidamountSql := sql.NewEsObject{}
  497. if tab.Sbidamount != "" {
  498. if strings.Contains(tab.Sbidamount, "大于") && strings.Contains(tab.Sbidamount, "小于") {
  499. arr := strings.Split(tab.Sbidamount, ",")
  500. limit := &sql.BudgetOrBidamount{
  501. Gte: util.Float64All(strings.Replace(arr[0], "大于", "", -1)),
  502. Lt: util.Float64All(strings.Replace(arr[1], "小于", "", -1)),
  503. }
  504. bidamountSql.Bool.Should = append(bidamountSql.Bool.Should, sql.BidamountMust{BidamountObj: &sql.BidamountObj{Bidamount: limit}})
  505. } else if strings.Contains(tab.Sbidamount, "大于") {
  506. limit := &sql.BudgetOrBidamount{
  507. Gte: util.Float64All(strings.Replace(tab.Sbidamount, "大于", "", -1)),
  508. }
  509. bidamountSql.Bool.Should = append(bidamountSql.Bool.Should, sql.BidamountMust{BidamountObj: &sql.BidamountObj{Bidamount: limit}})
  510. } else if strings.Contains(tab.Sbidamount, "小于") {
  511. limit := &sql.BudgetOrBidamount{
  512. Lt: util.Float64All(strings.Replace(tab.Sbidamount, "小于", "", -1)),
  513. }
  514. bidamountSql.Bool.Should = append(bidamountSql.Bool.Should, sql.BidamountMust{BidamountObj: &sql.BidamountObj{Bidamount: limit}})
  515. }
  516. if tab.SbidamountFieldExist == 1 {
  517. fqBoolObject.MustNot = append(fqBoolObject.MustNot, sql.ExistfieldsObjectMust{
  518. ExistfieldsObject: &sql.ExistfieldsObject{Filter: struct {
  519. Missing struct {
  520. Field string `json:"field,omitempty"`
  521. } `json:"missing,omitempty"`
  522. }{
  523. Missing: struct {
  524. Field string `json:"field,omitempty"`
  525. }{Field: "bidamount"},
  526. },
  527. },
  528. })
  529. }
  530. }
  531. budgetSql := sql.NewEsObject{}
  532. if tab.Sbudget != "" {
  533. if strings.Contains(tab.Sbudget, "大于") && strings.Contains(tab.Sbudget, "小于") {
  534. arr := strings.Split(tab.Sbudget, ",")
  535. limit := &sql.BudgetOrBidamount{
  536. Gte: util.Float64All(strings.Replace(arr[0], "大于", "", -1)),
  537. Lt: util.Float64All(strings.Replace(arr[1], "小于", "", -1)),
  538. }
  539. budgetSql.Bool.Should = append(budgetSql.Bool.Should, sql.BudgetMust{BudgetObj: &sql.BudgetObj{Budget: limit}})
  540. } else if strings.Contains(tab.Sbudget, "大于") {
  541. limit := &sql.BudgetOrBidamount{
  542. Gte: util.Float64All(strings.Replace(tab.Sbudget, "大于", "", -1)),
  543. }
  544. budgetSql.Bool.Should = append(budgetSql.Bool.Should, sql.BudgetMust{BudgetObj: &sql.BudgetObj{Budget: limit}})
  545. } else if strings.Contains(tab.Sbudget, "小于") {
  546. limit := &sql.BudgetOrBidamount{
  547. Lt: util.Float64All(strings.Replace(tab.Sbudget, "小于", "", -1)),
  548. }
  549. budgetSql.Bool.Should = append(budgetSql.Bool.Should, sql.BudgetMust{BudgetObj: &sql.BudgetObj{Budget: limit}})
  550. }
  551. if tab.SbudgetFieldExist == 1 {
  552. fqBoolObject.MustNot = append(fqBoolObject.MustNot, sql.ExistfieldsObjectMust{
  553. ExistfieldsObject: &sql.ExistfieldsObject{Filter: struct {
  554. Missing struct {
  555. Field string `json:"field,omitempty"`
  556. } `json:"missing,omitempty"`
  557. }{
  558. Missing: struct {
  559. Field string `json:"field,omitempty"`
  560. }{Field: "budget"},
  561. },
  562. },
  563. })
  564. }
  565. }
  566. if len(ffBoolObject.Must) > 0 || len(ffBoolObject.MustNot) > 0 || len(ffBoolObject.Should) > 0 {
  567. QueryObjecct.Bool = &ffBoolObject
  568. }
  569. if len(fqBoolObject.Must) > 0 || len(fqBoolObject.MustNot) > 0 || len(fqBoolObject.Should) > 0 {
  570. if QueryObjecct.Bool == nil {
  571. QueryObjecct.Bool = &fqBoolObject
  572. } else {
  573. if fqBoolObject.Must != nil {
  574. QueryObjecct.Bool.Must = append(QueryObjecct.Bool.Must, fqBoolObject.Must...)
  575. }
  576. if fqBoolObject.Should != nil {
  577. QueryObjecct.Bool.Should = append(QueryObjecct.Bool.Should, fqBoolObject.Should...)
  578. }
  579. if fqBoolObject.MustNot != nil {
  580. QueryObjecct.Bool.MustNot = append(QueryObjecct.Bool.MustNot, fqBoolObject.MustNot...)
  581. }
  582. }
  583. if len(torules.Should) > 0 {
  584. QueryObjecct.Bool.Must = append(QueryObjecct.Bool.Must, map[string]interface{}{
  585. "bool": torules,
  586. })
  587. }
  588. } else if len(torules.Should) > 0 {
  589. if QueryObjecct.Bool == nil {
  590. QueryObjecct.Bool = &sql.BoolObject{}
  591. }
  592. QueryObjecct.Bool.Must = append(QueryObjecct.Bool.Must, map[string]interface{}{
  593. "bool": torules,
  594. })
  595. }
  596. if (len(budgetSql.Bool.Should) > 0 || len(bidamountSql.Bool.Should) > 0) && (len(fqBoolObject.Must) > 0 || len(fqBoolObject.MustNot) > 0 || len(fqBoolObject.Should) > 0) {
  597. if QueryObjecct.Bool == nil {
  598. QueryObjecct.Bool = &sql.BoolObject{}
  599. }
  600. if len(budgetSql.Bool.Should) > 0 {
  601. QueryObjecct.Bool.Must = append(QueryObjecct.Bool.Must, budgetSql)
  602. }
  603. if len(bidamountSql.Bool.Should) > 0 {
  604. QueryObjecct.Bool.Must = append(QueryObjecct.Bool.Must, bidamountSql)
  605. }
  606. } else {
  607. if QueryObjecct.Bool == nil {
  608. QueryObjecct.Bool = &sql.BoolObject{}
  609. }
  610. if len(budgetSql.Bool.Should) > 0 {
  611. QueryObjecct.Bool.Must = append(QueryObjecct.Bool.Must, budgetSql)
  612. }
  613. if len(bidamountSql.Bool.Should) > 0 {
  614. QueryObjecct.Bool.Must = append(QueryObjecct.Bool.Must, bidamountSql)
  615. }
  616. }
  617. rdata := make(map[string]interface{})
  618. rdata["query"] = QueryObjecct
  619. esbytes, _ := json.Marshal(rdata)
  620. esStr := strings.Replace(string(esbytes), "regexp1", "regexp", -1)
  621. esStr = strings.Replace(esStr, "publishtime1", "publishtime", -1)
  622. esStr = strings.Replace(esStr, "publishtime2", "publishtime", -1)
  623. return strings.Replace(esStr, "regexp2", "regexp", -1)
  624. }
  625. func strsToArr(strs string, typestr string) []string {
  626. if len(strs) > 0 {
  627. tmps := strings.Split(strs, ",")
  628. switch typestr {
  629. case "str":
  630. for index, vint := range tmps {
  631. switch vint {
  632. case TitleMatchType:
  633. tmps[index] = TitleMatchTypeStr
  634. case DetailMatchType:
  635. tmps[index] = DetailMatchTypeStr
  636. case PurchasingMatchType:
  637. tmps[index] = PurchasingMatchTypeStr
  638. case AttachmentsMatchType:
  639. tmps[index] = AttachmentsMatchTypeStr
  640. case ProjectnameMatchType:
  641. tmps[index] = ProjectnameMatchTypeStr
  642. case BuyerMatchType:
  643. tmps[index] = BuyerMatchTypeStr
  644. case SWinnerMatchType:
  645. tmps[index] = SWinnerMatchTypeStr
  646. case BuyerMatchType1:
  647. tmps[index] = BuyerRegexpMatchTypeStr
  648. case SWinnerMatchType1:
  649. tmps[index] = SWinnerRegexpMatchTypeStr
  650. }
  651. }
  652. return tmps
  653. case "field":
  654. for index, vint := range tmps {
  655. switch vint {
  656. case TitleMatchType:
  657. tmps[index] = TitleMatchTypeField
  658. case DetailMatchType:
  659. tmps[index] = DetailMatchTypeField
  660. case PurchasingMatchType:
  661. tmps[index] = PurchasingMatchTypeField
  662. case AttachmentsMatchType:
  663. tmps[index] = AttachmentsMatchTypeField
  664. case ProjectnameMatchType:
  665. tmps[index] = ProjectnameMatchTypeField
  666. case BuyerMatchType:
  667. tmps[index] = BuyerMatchTypeField
  668. case SWinnerMatchType:
  669. tmps[index] = SWinnerMatchTypeField
  670. case BuyerMatchType1:
  671. tmps[index] = BuyerMatchTypeField
  672. case SWinnerMatchType1:
  673. tmps[index] = SWinnerMatchTypeField
  674. }
  675. }
  676. return tmps
  677. }
  678. }
  679. return nil
  680. }
  681. func init() {
  682. EsIndex = util.ObjToString(Sysconfig["elasticsearch_index"])
  683. EsType = util.ObjToString(Sysconfig["elasticsearch_type"])
  684. }
  685. func method1(newEsObject sql.NewEsObject, keyword, keymatch string, tmps []string) sql.NewEsObject {
  686. keywordArr := []string{}
  687. for _, vv := range strings.Split(keyword, ",") {
  688. if vv == "" {
  689. continue
  690. }
  691. //log.Println(vv, tmps, keymatch)
  692. if len(tmps) == 1 && (strings.Contains(keymatch, "8") || strings.Contains(keymatch, "9")) {
  693. //中标单位、采购单位、中标单位(正则)、采购单位(正则) 单选
  694. strs := ""
  695. if strings.Contains(vv, "&&") {
  696. //strs = ".*" + strings.Replace(vv, "&&", ".*", -1) + ".*"
  697. strs = strings.Replace(vv, "&&", ".*", -1)
  698. } else {
  699. strs = vv
  700. }
  701. if tmps[0] == "buyer.mbuyer" {
  702. newEsObject.Bool.Should = append(newEsObject.Bool.Should, sql.ShouldObj{
  703. MultiMatch: &sql.MultiMatch{
  704. Query: strs,
  705. Type: MultiMatchType,
  706. Fields: tmps,
  707. },
  708. })
  709. } else if tmps[0] == "s_winner.mwinner" {
  710. newEsObject.Bool.Should = append(newEsObject.Bool.Should, sql.ShouldObj{
  711. MultiMatch: &sql.MultiMatch{
  712. Query: strs,
  713. Type: MultiMatchType,
  714. Fields: tmps,
  715. },
  716. })
  717. }
  718. } else if len(tmps) == 1 && (strings.Contains(keymatch, "6") || strings.Contains(keymatch, "7")) {
  719. addkeylines := strings.Split(vv, "&&")
  720. keywordArr = append(keywordArr, addkeylines[0])
  721. } else {
  722. addkeylines := strings.Split(vv, "&&")
  723. //log.Println(addkeylines, "addkeylines")
  724. if len(addkeylines) > 1 {
  725. addkeyline := sql.NewEsObject{}
  726. for _, vvv := range addkeylines {
  727. if vvv == "" {
  728. continue
  729. }
  730. addkeyline.Bool.Must = append(addkeyline.Bool.Must, sql.ShouldObj{
  731. MultiMatch: &sql.MultiMatch{
  732. Query: vvv,
  733. Type: MultiMatchType,
  734. Fields: tmps,
  735. },
  736. })
  737. }
  738. if len(addkeyline.Bool.Must) > 0 {
  739. newEsObject.Bool.Should = append(newEsObject.Bool.Should, addkeyline)
  740. }
  741. } else {
  742. newEsObject.Bool.Should = append(newEsObject.Bool.Should, sql.ShouldObj{
  743. MultiMatch: &sql.MultiMatch{
  744. Query: vv,
  745. Type: MultiMatchType,
  746. Fields: tmps,
  747. },
  748. })
  749. }
  750. }
  751. }
  752. if len(tmps) == 1 && (strings.Contains(keymatch, "6") || strings.Contains(keymatch, "7")) {
  753. addkeyline := sql.NewEsObject{}
  754. if tmps[0] == "buyer" {
  755. addkeyline.Bool.Must = append(addkeyline.Bool.Must, sql.BuyerMatch{
  756. Buyer: &sql.Buyer{Buyer: keywordArr},
  757. })
  758. } else if tmps[0] == "s_winner" {
  759. addkeyline.Bool.Must = append(addkeyline.Bool.Must, sql.WinnerMatch{
  760. Winner: &sql.Winner{Winner: keywordArr},
  761. })
  762. }
  763. if len(addkeyline.Bool.Must) > 0 {
  764. newEsObject.Bool.Should = append(newEsObject.Bool.Should, addkeyline)
  765. }
  766. }
  767. return newEsObject
  768. }
  769. func method2(newEsObject sql.NewEsObject, keyword, keymatch string, tmps []string) sql.NewEsObject {
  770. notKeyWordArr := []string{}
  771. for _, vv := range strings.Split(keyword, ",") {
  772. if vv == "" {
  773. continue
  774. }
  775. if len(tmps) == 1 && (strings.Contains(keymatch, "8") || strings.Contains(keymatch, "9")) {
  776. //中标单位、采购单位、中标单位(正则)、采购单位(正则) 单选
  777. //strs := ""
  778. //if strings.Contains(vv, "&&") {
  779. // strs = ".*" + strings.Replace(vv, "&&", ".*", -1) + ".*"
  780. //} else {
  781. // strs = ".*" + vv + ".*"
  782. //}
  783. if tmps[0] == "buyer.mbuyer" {
  784. newEsObject.Bool.MustNot = append(newEsObject.Bool.MustNot, sql.ShouldObj{
  785. MultiMatch: &sql.MultiMatch{
  786. Query: vv,
  787. Type: MultiMatchType,
  788. Fields: tmps,
  789. },
  790. })
  791. } else if tmps[0] == "s_winner.mwinner" {
  792. newEsObject.Bool.MustNot = append(newEsObject.Bool.MustNot, sql.ShouldObj{
  793. MultiMatch: &sql.MultiMatch{
  794. Query: vv,
  795. Type: MultiMatchType,
  796. Fields: tmps,
  797. },
  798. })
  799. }
  800. } else if len(tmps) == 1 && (strings.Contains(keymatch, "6") || strings.Contains(keymatch, "7")) {
  801. notkeylines := strings.Split(vv, "&&")
  802. notKeyWordArr = append(notKeyWordArr, notkeylines[0])
  803. } else {
  804. notkeylines := strings.Split(vv, "&&")
  805. if len(notkeylines) > 1 {
  806. notkeyline := sql.NewEsObject{}
  807. for _, vvv := range notkeylines {
  808. if vvv == "" {
  809. continue
  810. }
  811. notkeyline.Bool.Must = append(notkeyline.Bool.Must, sql.ShouldObj{
  812. MultiMatch: &sql.MultiMatch{
  813. Query: vvv,
  814. Type: MultiMatchType,
  815. Fields: tmps,
  816. },
  817. })
  818. }
  819. if len(notkeyline.Bool.Must) > 0 {
  820. newEsObject.Bool.MustNot = append(newEsObject.Bool.MustNot, notkeyline)
  821. }
  822. } else {
  823. newEsObject.Bool.MustNot = append(newEsObject.Bool.MustNot, sql.ShouldObj{
  824. MultiMatch: &sql.MultiMatch{
  825. Query: vv,
  826. Type: MultiMatchType,
  827. Fields: tmps,
  828. },
  829. })
  830. }
  831. }
  832. }
  833. if len(tmps) == 1 && (strings.Contains(keymatch, "6") || strings.Contains(keymatch, "7")) {
  834. var notkeyline interface{}
  835. if tmps[0] == "buyer" {
  836. notkeyline = sql.BuyerMatch{
  837. Buyer: &sql.Buyer{Buyer: notKeyWordArr},
  838. }
  839. } else if tmps[0] == "s_winner" {
  840. notkeyline = sql.WinnerMatch{
  841. Winner: &sql.Winner{Winner: notKeyWordArr},
  842. }
  843. }
  844. if notkeyline != nil {
  845. newEsObject.Bool.MustNot = append(newEsObject.Bool.MustNot, notkeyline)
  846. }
  847. }
  848. return newEsObject
  849. }
  850. /**
  851. * 一级公告行业处理 d、t、p
  852. */
  853. func method3(arr []string) []string {
  854. var sArr []string
  855. for _, v := range arr {
  856. sArr = append(sArr, v+"d")
  857. sArr = append(sArr, v+"t")
  858. sArr = append(sArr, v+"p")
  859. }
  860. return sArr
  861. }
  862. func GetMactchKey(match []map[string]string, data map[string]interface{}) string {
  863. keyWord := []string{}
  864. for _, keys := range match {
  865. types := keys["s_keymatch"]
  866. key := keys["s_matchkey"]
  867. if strings.Contains(types, "1") {
  868. title := util.ObjToString(data["title"])
  869. keyWord = KeyWordToData(types, title, key, keyWord)
  870. }
  871. if strings.Contains(types, "2") {
  872. detail := util.ObjToString(data["detail"])
  873. keyWord = KeyWordToData(types, detail, key, keyWord)
  874. }
  875. if strings.Contains(types, "3") {
  876. purchasing := util.ObjToString(data["purchasing"])
  877. keyWord = KeyWordToData(types, purchasing, key, keyWord)
  878. }
  879. if strings.Contains(types, "4") {
  880. filetext := util.ObjToString(data["filetext"])
  881. keyWord = KeyWordToData(types, filetext, key, keyWord)
  882. }
  883. if strings.Contains(types, "5") {
  884. projectname := util.ObjToString(data["projectname"])
  885. keyWord = KeyWordToData(types, projectname, key, keyWord)
  886. }
  887. if strings.Contains(types, "6") || strings.Contains(types, "8") {
  888. buyer := util.ObjToString(data["buyer"])
  889. keyWord = KeyWordToData(types, buyer, key, keyWord)
  890. }
  891. if strings.Contains(types, "7") || strings.Contains(types, "9") {
  892. winner := util.ObjToString(data["s_winner"])
  893. keyWord = KeyWordToData(types, winner, key, keyWord)
  894. }
  895. }
  896. keyMap := map[string]bool{}
  897. keyArr := []string{}
  898. for _, key := range keyWord {
  899. keyMap[key] = true
  900. }
  901. for k, _ := range keyMap {
  902. keyArr = append(keyArr, k)
  903. }
  904. return strings.Join(keyArr, ",")
  905. }
  906. func KeyWordToData(types, item, key string, keyWord []string) []string {
  907. for _, mk := range strings.Split(key, ",") {
  908. if strings.Contains(mk, "&&") {
  909. arr := strings.Split(mk, "&&")
  910. isok := true
  911. for _, s := range arr {
  912. if s != "" {
  913. if !strings.Contains(strings.ToUpper(item), strings.ToUpper(s)) {
  914. isok = false
  915. }
  916. }
  917. }
  918. if isok {
  919. keyWord = append(keyWord, mk)
  920. }
  921. } else {
  922. if strings.Contains(strings.ToUpper(item), strings.ToUpper(mk)) {
  923. keyWord = append(keyWord, mk)
  924. }
  925. }
  926. }
  927. return keyWord
  928. }
  929. func GetProjectId(id string) string {
  930. query := `{"query": {"bool": {"must": [{"term": {"ids": "%s"}}],"must_not": [],"should": []}}}`
  931. querys := fmt.Sprintf(query, id)
  932. projectId := ""
  933. projectIdArr := []string{}
  934. data := Es.Get("projectset", "projectset", querys)
  935. if data != nil && *data != nil && len(*data) > 0 {
  936. for _, v := range *data {
  937. projectIdArr = append(projectIdArr, util.ObjToString(v["_id"]))
  938. }
  939. projectId = strings.Join(projectIdArr, ",")
  940. log.Println("projectId", projectId)
  941. } else {
  942. log.Println("ES未查到项目id", id)
  943. }
  944. return projectId
  945. }