dataexport.go 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282
  1. package dataexport
  2. import (
  3. //"config"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "log"
  8. "math"
  9. "regexp"
  10. "sort"
  11. "strconv"
  12. "strings"
  13. "sync"
  14. "time"
  15. qutil "app.yhyue.com/moapp/jybase/common"
  16. . "app.yhyue.com/moapp/jybase/date"
  17. . "app.yhyue.com/moapp/jybase/encrypt"
  18. elastic "app.yhyue.com/moapp/jybase/es"
  19. mg "app.yhyue.com/moapp/jybase/mongodb"
  20. "app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
  21. )
  22. const (
  23. SearchModeAccurate = 0 // 搜索模式:0:精准搜索;
  24. SearchModeFuzzy = 1 // 搜索模式:1:模糊搜索
  25. WordsModeAnd = 0 // 搜索关键词模式;默认0:包含所有
  26. WordsModeOr = 1 // 搜索关键词模式;1:包含任意
  27. SearchGroupAll = 0 // 搜索分组:默认0:全部;
  28. SearchGroupBidding = 1 // 搜索分组:1:招标采购公告;2:超前项目
  29. SearchGroupLeadingProject = 2 // 搜索分组:1:招标采购公告;2:超前项目
  30. TopTypesBidding = "招标预告,招标公告,招标结果,招标信用信息"
  31. TopTypesLeadingProject = "拟建项目,采购意向"
  32. )
  33. /*筛选条件--关键词*/
  34. type KeyWord struct {
  35. Keyword string `json:"keyword"` //关键词
  36. Appended []string `json:"appended"` //附加词
  37. Exclude []string `json:"exclude"` //排除词
  38. }
  39. /*筛选条件*/
  40. type SieveCondition struct {
  41. Id string `json:"id"`
  42. PublishTime string `json:"publishtime"` //发布时间
  43. Area []string `json:"area"` //地区-省份
  44. City []string `json:"city"` //地区-城市
  45. Region []string `json:"region"` //地区-省份+城市
  46. Industry []string `json:"industry"` //行业
  47. Keyword []KeyWord `json:"keywords"` //关键词
  48. Buyer []string `json:"buyer"` //招标单位(采购单位)
  49. Buyerclass []string `json:"buyerclass"` //采购单位类型
  50. HasBuyerTel string `json:"hasBuyertel"` //是否有采购单位电话
  51. Winner []string `json:"winner"` //中标单位
  52. HasWinnerTel string `json:"hasWinnertel"` //是否有中标单位电话
  53. ComeInTime int64 `json:"comeintime"` //入库时间(秒)
  54. OpenId string `json:"openid"` //用户openid
  55. MinPrice string `json:"minprice"` //金额——最少
  56. MaxPrice string `json:"maxprice"` //金额——最多
  57. SelectType string `json:"selectType"` //筛选(正文 or 标题)
  58. Subtype string `json:"subtype"` //信息类型
  59. SelectIds []string `json:"selectId"` //选择信息导出
  60. PushKeyWords []string `json:"pushKeyWords"` //推送历史匹配词
  61. Comeinfrom string `json:"comeinfrom"` //查询来源
  62. FileExists string `json:"fileExists"` //是否有附件
  63. SearchTypeSwitch bool `json:"searchTypeSwitch"` //是否开启 正文 标题同时搜索只搜正文的开关
  64. BidField string `json:"bid_field"` // 领域化数据 0101-医疗行业
  65. SearchGroup int `json:"searchGroup"` // 搜索分组:默认0:全部;1:招标采购公告;2:超前项目
  66. SearchMode int `json:"searchMode"` // 搜索模式:0:精准搜索;1:模糊搜索
  67. WordsMode int `json:"wordsMode"` // 搜索关键词模式;默认0:包含所有,1:包含任意
  68. }
  69. const (
  70. INDEX = "bidding"
  71. TYPE = "bidding"
  72. bidSearch_sort = `{"publishtime":-1}`
  73. )
  74. var ClearOther = regexp.MustCompile("[\n\r\\s\u3000\u2003\u00a0]")
  75. var ClearHtml = regexp.MustCompile("<[^>]*>")
  76. var onceSearchCount = 500
  77. var ExportTable string = "export_search"
  78. var searchPool = make(chan bool, 8)
  79. var topType = map[string]string{
  80. "招标预告": "预告",
  81. "招标公告": "招标",
  82. "招标结果": "结果",
  83. "招标信用信息": "其它",
  84. "拟建项目": "拟建",
  85. "采购意向": "采购意向",
  86. }
  87. // 包含正文或 附件 不包含标题
  88. func DetailFileORTitle(findfields string) bool {
  89. return (strings.Contains(findfields, "detail") || strings.Contains(findfields, "filetext")) && !strings.Contains(findfields, "title")
  90. }
  91. // 包含正文包含标题
  92. func DetailANDTitle(findfields string) bool {
  93. return strings.Contains(findfields, "detail") && strings.Contains(findfields, "title")
  94. }
  95. // 获取数据导出查询语句
  96. func getDataExportSql(scd *SieveCondition) string {
  97. if len(scd.SelectIds) > 0 {
  98. query := `{"query":{"bool":{"must":[%s]}}}`
  99. doSearchSql := fmt.Sprintf(`{"terms":{"_id":[%s]}}`, `"`+strings.Join(scd.SelectIds, `","`)+`"`)
  100. return fmt.Sprintf(query, doSearchSql)
  101. }
  102. multi_match := `{"multi_match": {"query": %s,"type": "phrase", "fields": [%s]}}`
  103. query := `{"query":{"bool":{"filter":[%s],"must_not":[%s],"should":[%s],"minimum_should_match": %d}}}`
  104. //query := `{"query": {"function_score": {"query": {"bool": {"must": [%s],"must_not": [%s],"should": [%s],"minimum_should_match": %d}},"field_value_factor": {"field": "dataweight","modifier": "ln1p","missing": 0}}}}`
  105. query_bool_should := `{"bool":{"should":[%s],"minimum_should_match": 1}}`
  106. query_bool_should_and := `{"bool":{"should":[%s],"minimum_should_match": 1 %s}}`
  107. query_price := `{"bool":{"must":[{"range":{"bidamount":{%s}}}]}},{"bool":{"must":[{"range":{"budget":{%s}}}],"must_not":[{"range":{"bidamount":{"gte":-1}}}]}}`
  108. query_bool_must := `{"terms":{"%s":[%s]}}`
  109. query_bool_must_and := `{"bool":{"must":[%s]%s}}`
  110. query_exists := `{"constant_score":{"filter":{"exists":{"field":"%s"}}}}`
  111. query_bool_must_term := `{"bool": {"must": [{ "term": {"isValidFile": %t }}]}}`
  112. query_bool_must_term_bidField := `{"bool": {"must": [{ "term": {"bid_field": "%s" }}]}}` // 领域化数据类型
  113. gte := `"gte": %s`
  114. lte := `"lte": %s`
  115. bools := []string{}
  116. musts := []string{fmt.Sprintf(`{"range":{"comeintime":{"lt":%d}}}`, scd.ComeInTime)}
  117. must_not := []string{}
  118. //省份
  119. areaCity := []string{}
  120. if len(scd.Area) > 0 {
  121. areaquery := `{"terms":{"area":[`
  122. for k, v := range scd.Area {
  123. if k > 0 {
  124. areaquery += `,`
  125. }
  126. areaquery += `"` + v + `"`
  127. }
  128. areaquery += `]}}`
  129. areaCity = append(areaCity, areaquery)
  130. }
  131. //城市
  132. if len(scd.City) > 0 {
  133. areaquery := `{"terms":{"city":[`
  134. for k, v := range scd.City {
  135. if k > 0 {
  136. areaquery += `,`
  137. }
  138. areaquery += `"` + v + `"`
  139. }
  140. areaquery += `]}}`
  141. areaCity = append(areaCity, areaquery)
  142. }
  143. if len(areaCity) > 0 {
  144. musts = append(musts, fmt.Sprintf(query_bool_should, strings.Join(areaCity, ",")))
  145. }
  146. //检索日期
  147. starttime := ""
  148. now := time.Unix(scd.ComeInTime, 0)
  149. endtime := fmt.Sprintf("%d", now.Unix())
  150. if scd.PublishTime == "lately-7" { //最近7天
  151. starttime = fmt.Sprint(time.Date(now.Year(), now.Month(), now.Day()-7, 0, 0, 0, 0, time.Local).Unix())
  152. } else if scd.PublishTime == "lately-30" { //最近30天
  153. starttime = fmt.Sprint(time.Date(now.Year(), now.Month(), now.Day()-30, 0, 0, 0, 0, time.Local).Unix())
  154. } else if scd.PublishTime == "thisyear" { //去年
  155. starttime = fmt.Sprint(time.Date(now.Year()-1, 1, 1, 0, 0, 0, 0, time.Local).Unix())
  156. endtime = fmt.Sprint(time.Date(now.Year()-1, 12, 31, 23, 59, 59, 0, time.Local).Unix())
  157. } else if strings.Contains(scd.PublishTime, "_") { //设置检索日期
  158. starttime = strings.Split(scd.PublishTime, "_")[0]
  159. endTime_tmp := now
  160. if etime := strings.Split(scd.PublishTime, "_")[1]; etime != "" {
  161. etTime := time.Unix(qutil.Int64All(etime), 0)
  162. endTime_tmp = time.Date(etTime.Year(), etTime.Month(), etTime.Day()+1, 0, 0, 0, 0, time.Local)
  163. }
  164. //结束时间必须小于筛选时间
  165. if endTime_tmp.After(now) {
  166. endTime_tmp = now
  167. }
  168. endtime = fmt.Sprintf("%d", endTime_tmp.Unix())
  169. }
  170. timequery := `{"range":{"publishtime":{`
  171. if starttime != "" {
  172. timequery += `"gte":` + starttime
  173. }
  174. if starttime != "" && endtime != "" {
  175. timequery += `,`
  176. }
  177. if endtime != "" {
  178. timequery += `"lt":` + endtime
  179. }
  180. timequery += `}}}`
  181. musts = append(musts, timequery)
  182. if scd.Subtype == "" {
  183. if scd.SearchGroup == SearchGroupBidding { // 搜索分组处理 招标采购公告 超前项目
  184. scd.Subtype = TopTypesBidding
  185. } else if scd.SearchGroup == SearchGroupLeadingProject {
  186. scd.Subtype = TopTypesLeadingProject
  187. }
  188. }
  189. if scd.Subtype != "" {
  190. var subquery string
  191. var topTypes []string
  192. var subTypes []string
  193. for _, v := range strings.Split(scd.Subtype, ",") {
  194. if v1, ok := topType[v]; ok {
  195. topTypes = append(topTypes, fmt.Sprintf(`"%s"`, v1))
  196. } else {
  197. subTypes = append(subTypes, fmt.Sprintf(`"%s"`, v))
  198. }
  199. }
  200. log.Println("信息类型搜索:", topTypes, subTypes)
  201. if len(subTypes) > 0 && len(topTypes) > 0 {
  202. subquery = fmt.Sprintf(`{"bool": {"should": [{"terms": {"subtype": [%s]}},{"terms": {"toptype": [%s]}}]}}`, strings.Join(subTypes, ","), strings.Join(topTypes, ","))
  203. } else if len(subTypes) > 0 {
  204. subquery = fmt.Sprintf(`{"terms":{"subtype":[%s]}}`, strings.Join(subTypes, ","))
  205. } else if len(topTypes) > 0 {
  206. subquery = fmt.Sprintf(`{"terms":{"toptype":[%s]}}`, strings.Join(topTypes, ","))
  207. }
  208. musts = append(musts, subquery)
  209. }
  210. if len(scd.Industry) > 0 {
  211. musts = append(musts, fmt.Sprintf(query_bool_must, "s_subscopeclass", `"`+strings.Join(scd.Industry, `","`)+`"`))
  212. }
  213. if len(scd.Buyer) > 0 {
  214. musts = append(musts, fmt.Sprintf(query_bool_must, "buyer", `"`+strings.Join(scd.Buyer, `","`)+`"`))
  215. }
  216. if len(scd.Buyerclass) > 0 {
  217. musts = append(musts, fmt.Sprintf(query_bool_must, "buyerclass", `"`+strings.Join(scd.Buyerclass, `","`)+`"`))
  218. }
  219. if len(scd.Winner) > 0 {
  220. musts = append(musts, fmt.Sprintf(query_bool_must, "s_winner", `"`+strings.Join(scd.Winner, `","`)+`"`))
  221. }
  222. _minPrice := ""
  223. _maxPrice := ""
  224. if scd.MinPrice != "" || scd.MaxPrice != "" {
  225. sq := ``
  226. if scd.MinPrice != "" {
  227. min, _ := strconv.ParseFloat(scd.MinPrice, 64)
  228. _minPrice = fmt.Sprintf("%.0f", min*10000)
  229. if _minPrice == "0" {
  230. _minPrice = ""
  231. }
  232. }
  233. if scd.MaxPrice != "" {
  234. max, _ := strconv.ParseFloat(scd.MaxPrice, 64)
  235. _maxPrice = fmt.Sprintf("%.0f", max*10000)
  236. if _maxPrice == "0" {
  237. _maxPrice = ""
  238. }
  239. }
  240. if _minPrice != "" {
  241. sq += fmt.Sprintf(gte, _minPrice)
  242. }
  243. if _minPrice != "" && _maxPrice != "" {
  244. sq += `,`
  245. }
  246. if _maxPrice != "" {
  247. sq += fmt.Sprintf(lte, _maxPrice)
  248. }
  249. if _minPrice != "" || _maxPrice != "" {
  250. query_price := fmt.Sprintf(query_bool_should, fmt.Sprintf(query_price, sq, sq))
  251. musts = append(musts, query_price)
  252. }
  253. }
  254. boolsNum := 0
  255. selectType := scd.SelectType
  256. //should
  257. if len(scd.Keyword) > 0 {
  258. boolsNum = 1
  259. queryItem := ""
  260. if selectType == "" {
  261. queryItem = "title"
  262. } else if selectType == "all" {
  263. queryItem = "detail\", \"title"
  264. } else {
  265. if scd.SearchTypeSwitch && DetailANDTitle(selectType) {
  266. if strings.Contains(selectType, "title,") {
  267. selectType = strings.Replace(selectType, "title,", "", -1)
  268. } else if strings.Contains(selectType, ",title") {
  269. selectType = strings.Replace(selectType, ",title", "", -1)
  270. }
  271. }
  272. selectMap := map[string]bool{}
  273. for _, key := range strings.Split(selectType, ",") {
  274. selectMap[key] = true
  275. }
  276. //todo: 领导说:如果前三个都有,拼语句的时候忽略第四个吧
  277. if scd.Comeinfrom == "exportPage" && selectMap["detail"] && selectMap["filetext"] && selectMap["title"] {
  278. delete(selectMap, "purchasing")
  279. delete(selectMap, "projectname.pname")
  280. }
  281. if len(selectMap) > 0 {
  282. var arr []string
  283. for key, _ := range selectMap {
  284. arr = append(arr, key)
  285. }
  286. queryItem = strings.Join(arr, "\",\"")
  287. }
  288. }
  289. multi_match_new := fmt.Sprintf(multi_match, "%s", "\""+queryItem+"\"")
  290. if scd.Comeinfrom == "supersearchPage" {
  291. var keywordArr []string
  292. if strings.Contains(scd.Keyword[0].Keyword, "+") {
  293. //keywordArr = strings.Split(scd.Keyword[0].Keyword, "+")
  294. } else if strings.Contains(scd.Keyword[0].Keyword, " ") {
  295. //keywordArr = strings.Split(scd.Keyword[0].Keyword, " ")
  296. }
  297. if len(keywordArr) > 1 {
  298. KeyWordSearch := KeyWord{}
  299. for _, v := range keywordArr {
  300. KeyWordSearch.Appended = append(KeyWordSearch.Appended, v)
  301. }
  302. scd.Keyword = []KeyWord{KeyWordSearch}
  303. }
  304. }
  305. for _, v := range scd.Keyword {
  306. shoulds := []string{}
  307. must_not := []string{}
  308. keysShoulds := []string{}
  309. if v.Keyword != "" {
  310. if strings.Contains(v.Keyword, "+") {
  311. for _, vk := range strings.Split(v.Keyword, "+") {
  312. if len(vk) == 0 {
  313. continue
  314. }
  315. //单个字 搜索范围 有全文或者附件 无标题 例如:学 虚拟机 detail 搜索的时候加上标题
  316. if scd.Comeinfrom == "supersearchPage" && DetailFileORTitle(selectType) && len([]rune(elastic.ReplaceYH(vk))) == 1 {
  317. queryItem = strings.ReplaceAll(selectType+",title", ",", "\",\"")
  318. shouldsKey := fmt.Sprintf(multi_match, "\""+vk+"\"", "\""+queryItem+"\"")
  319. keysShoulds = append(keysShoulds, shouldsKey)
  320. } else {
  321. keysShoulds = append(keysShoulds, fmt.Sprintf(multi_match_new, "\""+vk+"\""))
  322. }
  323. }
  324. } else if strings.Contains(v.Keyword, " ") {
  325. for _, vk := range strings.Split(v.Keyword, " ") {
  326. if len(vk) == 0 {
  327. continue
  328. }
  329. //单个字 搜索范围 有全文或者附件 无标题 例如:学 虚拟机 detail 搜索的时候加上标题
  330. if scd.Comeinfrom == "supersearchPage" && DetailFileORTitle(selectType) && len([]rune(elastic.ReplaceYH(vk))) == 1 {
  331. queryItem = strings.ReplaceAll(selectType+",title", ",", "\",\"")
  332. shouldsKey := fmt.Sprintf(multi_match, "\""+vk+"\"", "\""+queryItem+"\"")
  333. keysShoulds = append(keysShoulds, shouldsKey)
  334. } else {
  335. keysShoulds = append(keysShoulds, fmt.Sprintf(multi_match_new, "\""+vk+"\""))
  336. }
  337. }
  338. } else {
  339. //单个字 搜索范围 有全文或者附件 无标题 例如:学 虚拟机 detail 搜索的时候加上标题
  340. if scd.Comeinfrom == "supersearchPage" && DetailFileORTitle(selectType) && len([]rune(elastic.ReplaceYH(v.Keyword))) == 1 {
  341. queryItem = strings.ReplaceAll(selectType+",title", ",", "\",\"")
  342. shouldsKey := fmt.Sprintf(multi_match, "\""+v.Keyword+"\"", "\""+queryItem+"\"")
  343. keysShoulds = append(keysShoulds, shouldsKey)
  344. } else {
  345. keysShoulds = append(keysShoulds, fmt.Sprintf(multi_match_new, "\""+v.Keyword+"\""))
  346. }
  347. }
  348. // 单个关键词分词后都包含
  349. shoulds = append(shoulds, fmt.Sprintf(query_bool_must_and, strings.Join(keysShoulds, ","), ""))
  350. }
  351. //附加词
  352. for _, vv := range v.Appended {
  353. appendedShoulds := []string{}
  354. if vv != "" {
  355. // 附加词处理分词
  356. if strings.Contains(vv, "+") {
  357. for _, vk := range strings.Split(vv, "+") {
  358. if len(vk) == 0 {
  359. continue
  360. }
  361. //单个字 搜索范围 有全文或者附件 无标题 例如:学 虚拟机 detail 搜索的时候加上标题
  362. if scd.Comeinfrom == "supersearchPage" && DetailFileORTitle(selectType) && len([]rune(elastic.ReplaceYH(vk))) == 1 {
  363. queryItem = strings.ReplaceAll(selectType+",title", ",", "\",\"")
  364. shouldsKey := fmt.Sprintf(multi_match, "\""+vk+"\"", "\""+queryItem+"\"")
  365. appendedShoulds = append(appendedShoulds, shouldsKey)
  366. } else {
  367. appendedShoulds = append(appendedShoulds, fmt.Sprintf(multi_match_new, "\""+vk+"\""))
  368. }
  369. }
  370. } else {
  371. for _, vk := range strings.Split(vv, " ") {
  372. if len(vk) == 0 {
  373. continue
  374. }
  375. //单个字 搜索范围 有全文或者附件 无标题 例如:学 虚拟机 detail 搜索的时候加上标题
  376. if scd.Comeinfrom == "supersearchPage" && DetailFileORTitle(selectType) && len([]rune(elastic.ReplaceYH(vk))) == 1 {
  377. queryItem = strings.ReplaceAll(selectType+",title", ",", "\",\"")
  378. shouldsKey := fmt.Sprintf(multi_match, "\""+vk+"\"", "\""+queryItem+"\"")
  379. appendedShoulds = append(appendedShoulds, shouldsKey)
  380. } else {
  381. appendedShoulds = append(appendedShoulds, fmt.Sprintf(multi_match_new, "\""+vk+"\""))
  382. }
  383. }
  384. }
  385. // 单个关键词分词后都包含
  386. shoulds = append(shoulds, fmt.Sprintf(query_bool_must_and, strings.Join(appendedShoulds, ","), ""))
  387. }
  388. }
  389. //排除词
  390. for _, vv := range v.Exclude {
  391. if len(strings.TrimSpace(vv)) == 0 {
  392. continue
  393. } // 处理每组里面的空格分词
  394. for _, notKeySplit := range strings.Split(vv, " ") {
  395. if len(notKeySplit) == 0 {
  396. continue
  397. }
  398. //单个字 搜索范围 有全文或者附件 无标题 例如:学 虚拟机 detail 搜索的时候加上标题
  399. if scd.Comeinfrom == "supersearchPage" && DetailFileORTitle(selectType) && len([]rune(elastic.ReplaceYH(notKeySplit))) == 1 {
  400. queryItem = strings.ReplaceAll(selectType+",title", ",", "\",\"")
  401. shouldsKey := fmt.Sprintf(multi_match, "\""+notKeySplit+"\"", "\""+queryItem+"\"")
  402. must_not = append(must_not, shouldsKey)
  403. } else {
  404. must_not = append(must_not, fmt.Sprintf(multi_match_new, "\""+notKeySplit+"\""))
  405. }
  406. }
  407. }
  408. //添加
  409. if len(shoulds) > 0 {
  410. notStr := ""
  411. if len(must_not) > 0 {
  412. notStr = fmt.Sprintf(`,"must_not":[%s]`, strings.Join(must_not, ","))
  413. }
  414. if scd.WordsMode == WordsModeOr { // 包含任意
  415. bools = append(bools, fmt.Sprintf(query_bool_should_and, strings.Join(shoulds, ","), notStr))
  416. } else {
  417. bools = append(bools, fmt.Sprintf(query_bool_must_and, strings.Join(shoulds, ","), notStr))
  418. }
  419. }
  420. }
  421. }
  422. if scd.HasBuyerTel != "" {
  423. if scd.HasBuyerTel == "y" {
  424. musts = append(musts, fmt.Sprintf(query_exists, "buyertel"))
  425. } else {
  426. must_not = append(must_not, fmt.Sprintf(query_exists, "buyertel"))
  427. }
  428. }
  429. if scd.HasWinnerTel != "" {
  430. if scd.HasWinnerTel == "y" {
  431. musts = append(musts, fmt.Sprintf(query_exists, "winnertel"))
  432. } else {
  433. must_not = append(must_not, fmt.Sprintf(query_exists, "winnertel"))
  434. }
  435. }
  436. //搜索范围是否只有附件
  437. //搜索范围只选择附件,是否有附件条件无效;
  438. var isFileSearch = strings.ReplaceAll(selectType, ",", "\",\"") == "filetext"
  439. if !isFileSearch && scd.FileExists != "" {
  440. if scd.FileExists == "1" { //有附件
  441. musts = append(musts, fmt.Sprintf(query_bool_must_term, true))
  442. } else if scd.FileExists == "-1" { //无附件
  443. must_not = append(must_not, fmt.Sprintf(query_bool_must_term, true))
  444. }
  445. }
  446. // 如果是领域化数据则需要加标签
  447. if scd.BidField != "" {
  448. musts = append(musts, fmt.Sprintf(query_bool_must_term_bidField, scd.BidField))
  449. }
  450. qstr := fmt.Sprintf(query, strings.Join(musts, ","), strings.Join(must_not, ","), strings.Join(bools, ","), boolsNum)
  451. return qstr
  452. }
  453. // 获取数据导出筛选条件
  454. func GetSqlObjFromId(mongo mg.MongodbSim, _id string) *SieveCondition {
  455. var (
  456. query *map[string]interface{}
  457. ok bool
  458. )
  459. if query, ok = mongo.FindById(ExportTable, _id, nil); !ok {
  460. return nil
  461. }
  462. searchTypeSwitch, _ := (*query)["searchTypeSwitch"].(bool)
  463. return &SieveCondition{
  464. Id: _id,
  465. Keyword: getKeyWordArrFromDbResult((*query)["keywords"]),
  466. Industry: getStringArrFromDbResult((*query)["industry"]),
  467. MinPrice: qutil.ObjToString((*query)["minprice"]),
  468. MaxPrice: qutil.ObjToString((*query)["maxprice"]),
  469. Subtype: qutil.ObjToString((*query)["subtype"]),
  470. Area: getStringArrFromDbResult((*query)["area"]),
  471. City: getStringArrFromDbResult((*query)["city"]),
  472. SelectType: qutil.ObjToString((*query)["selectType"]),
  473. PublishTime: qutil.ObjToString((*query)["publishtime"]),
  474. Buyer: getStringArrFromDbResult((*query)["buyer"]),
  475. Buyerclass: getStringArrFromDbResult((*query)["buyerclass"]),
  476. HasBuyerTel: qutil.ObjToString((*query)["hasBuyertel"]),
  477. Winner: getStringArrFromDbResult((*query)["winner"]),
  478. HasWinnerTel: qutil.ObjToString((*query)["hasWinnertel"]),
  479. ComeInTime: qutil.Int64All((*query)["comeintime"]),
  480. Comeinfrom: qutil.ObjToString((*query)["comeinfrom"]),
  481. SelectIds: getStringArrFromDbResult((*query)["selectIds"]),
  482. PushKeyWords: getStringArrFromDbResult((*query)["pushKeyWords"]),
  483. FileExists: qutil.ObjToString((*query)["fileExists"]),
  484. SearchTypeSwitch: searchTypeSwitch,
  485. BidField: qutil.ObjToString((*query)["bid_field"]), // 领域化数据
  486. SearchGroup: qutil.IntAll((*query)["searchGroup"]), //搜索分组:默认0:全部;1:招标采购公告;2:超前项目
  487. SearchMode: qutil.IntAll((*query)["searchMode"]), // 搜索模式:0:精准搜索;1:模糊搜索
  488. WordsMode: qutil.IntAll((*query)["wordsMode"]), // 搜索关键词模式;默认0:包含所有,1:包含任意
  489. }
  490. }
  491. // 数据导出-查询结果数量
  492. func GetDataExportSearchCountByScdId(sim mg.MongodbSim, elasticAddress, id string) (count int) {
  493. scd := GetSqlObjFromId(sim, id) //用户筛选条件
  494. if scd.SelectIds != nil {
  495. //部分数据可能已删除、不存在;此处需要统计返回实际数量
  496. //return len(scd.SelectIds)
  497. return int(GetDataExportSelectReallyCount(scd.SelectIds))
  498. }
  499. return GetDataExportSearchCountBySieveCondition(scd, elasticAddress)
  500. }
  501. func GetDataExportSearchCountBySieveCondition(scd *SieveCondition, elasticAddress string) (count int) {
  502. if isNullSearch(scd) {
  503. return -1 //程序端返回最大值
  504. }
  505. if scd.SearchMode == SearchModeAccurate {
  506. qstr := getDataExportSql(scd)
  507. log.Printf("GetDataExportSearchCountUseId-%s-sql:%s\n", scd.Id, qstr)
  508. count = int(elastic.Count(INDEX, TYPE, qstr))
  509. }
  510. // 依据用户选择的搜索模式和搜索范围进行匹配,即不限制只能匹配标题,且不限制最多展示100条、针对输入的单个关键词分词后需要都包含
  511. //超级搜索一致的检索(防止数据导出和超级搜索数据量不一致)
  512. if scd.Comeinfrom == "supersearchPage" && (len(scd.Keyword) != 0 || len(scd.Industry) != 0) && scd.SearchMode == SearchModeFuzzy {
  513. if len(scd.Keyword) != 0 {
  514. // 关键词分词
  515. searchTextSize := 0
  516. if len(scd.Keyword) > 0 {
  517. searchTextSize = len([]rune(scd.Keyword[0].Keyword))
  518. }
  519. if searchTextSize > 0 {
  520. if secondKWS := jy.HttpEs(scd.Keyword[0].Keyword, "ik_smart", elasticAddress); secondKWS != "" {
  521. scd.Keyword[0].Keyword = jy.KeywordsProcessing(strings.ReplaceAll(secondKWS, "+", " "), " ")
  522. }
  523. }
  524. // 附加词分词
  525. for i := 0; i < len(scd.Keyword[0].Appended); i++ {
  526. appendTextSize := 0
  527. if len(scd.Keyword[0].Appended[i]) > 0 {
  528. appendTextSize = len([]rune(scd.Keyword[0].Appended[i]))
  529. }
  530. if appendTextSize > 0 {
  531. if secondKWS := jy.HttpEs(scd.Keyword[0].Appended[i], "ik_smart", elasticAddress); secondKWS != "" {
  532. scd.Keyword[0].Appended[i] = jy.KeywordsProcessing(strings.ReplaceAll(secondKWS, "+", " "), " ")
  533. }
  534. }
  535. }
  536. }
  537. qstr := getDataExportSql(scd)
  538. count = int(elastic.Count(INDEX, TYPE, qstr))
  539. log.Printf("GetDataExportSearchCountUseId-%s-count:%d-分词-sql:%s\n", scd.Id, count, qstr)
  540. return count
  541. }
  542. log.Printf("GetDataExportSearchCountUseId-%s-count:%d\n", scd.Id, count)
  543. return
  544. }
  545. // 合并map数据,去重
  546. func delRepeatMapArr(res *[]map[string]interface{}, res2 *[]map[string]interface{}) *[]map[string]interface{} {
  547. if res != nil {
  548. for _, v := range *res {
  549. for n, m := range *res2 {
  550. if qutil.ObjToString(v["_id"]) == qutil.ObjToString(m["_id"]) {
  551. *res2 = append((*res2)[0:n], (*res2)[n+1:]...)
  552. break
  553. }
  554. }
  555. }
  556. *res = append(*res, *res2...)
  557. } else {
  558. res = res2
  559. }
  560. return res
  561. }
  562. // 查询条件是否为空
  563. func isNullSearch(scd *SieveCondition) (isNull bool) {
  564. if scd.PublishTime == "" && len(scd.Area) == 0 && len(scd.Industry) == 0 && len(scd.Keyword) == 0 && len(scd.Buyer) == 0 && len(scd.Winner) == 0 && scd.MinPrice == "" && scd.MaxPrice == "" && scd.Subtype == "" && len(scd.City) == 0 {
  565. isNull = true
  566. }
  567. return isNull
  568. }
  569. /*
  570. * 数据导出 查询结果
  571. * _id 数据库查询条件记录id
  572. * dataType 1-普通字段 2-高级字段
  573. * webdomain 三级页域名
  574. * count 返回数量 (-1:预览数据查询)
  575. */
  576. func GetDataExportSearchResultByScdId(sim mg.MongodbSim, elasticAddress, id, dataType string, checkCount int) (*[]map[string]interface{}, error) {
  577. scd := GetSqlObjFromId(sim, id)
  578. list, err := GetDataExportSearchResult(elasticAddress, scd, dataType, checkCount)
  579. if list == nil || err != nil {
  580. return nil, err
  581. }
  582. return list, nil
  583. }
  584. // GetDataExportIdArrByScdId 数据包去重获取导出信息id
  585. func GetDataExportIdArrByScdId(sim mg.MongodbSim, elasticAddress, id string, checkCount int) ([]string, error) {
  586. scd := GetSqlObjFromId(sim, id)
  587. return GetDataExportIds(elasticAddress, scd, checkCount)
  588. }
  589. // 收藏导出
  590. var contentfilterReg = regexp.MustCompile("<[^>]+>")
  591. // GetDataExportSelectReallyCount 查询实际可调导出数量
  592. func GetDataExportSelectReallyCount(ids []string) int64 {
  593. pool := make(chan bool, 10)
  594. wait := &sync.WaitGroup{}
  595. var total int64
  596. var lock sync.Mutex
  597. for _, v := range SplitArray(ids, 200) {
  598. pool <- true
  599. wait.Add(1)
  600. go func(arr []string) {
  601. defer func() {
  602. wait.Done()
  603. <-pool
  604. }()
  605. query := fmt.Sprintf(`{"query":{"bool":{"must":[{"terms":{"id":["%s"]}}]}}}`, strings.Join(arr, "\",\""))
  606. tCount := elastic.Count(INDEX, TYPE, query)
  607. if tCount > 0 {
  608. lock.Lock()
  609. total += tCount
  610. lock.Unlock()
  611. }
  612. return
  613. }(v)
  614. }
  615. wait.Wait()
  616. log.Printf("GetDataExportSelectReallyCount 选择数据共%d条记录,实际查询%d条\n", len(ids), total)
  617. return total
  618. }
  619. func GetDataExportSelectResult(scd *SieveCondition, dataType string, checkCount int) (*[]map[string]interface{}, error) {
  620. //sess := bidding.GetMgoConn()
  621. //defer bidding.DestoryMongoConn(sess)
  622. bidField := `"_id", "title", "detail", "area", "city", "publishtime", "projectname", "buyer", "s_winner", "bidamount", "subtype", "toptype", "filetext", "purchasing"`
  623. //selectMap := map[string]interface{}{
  624. // "_id": 1, "title": 1, "detail": 1, "area": 1, "city": 1, "publishtime": 1, "projectname": 1, "buyer": 1, "s_winner": 1, "bidamount": 1, "subtype": 1, "toptype": 1, "filetext": 1, "purchasing": 1,
  625. //}
  626. if dataType == "2" {
  627. bidField = bidField + `,"href", "projectcode", "buyerperson", "buyertel", "budget", "bidopentime", "agency", "projectscope", "winnerperson", "winnertel", "bidendtime", "district", "signendtime", "buyeraddr","buyerclass","s_topscopeclass","entidlist"`
  628. //for _, key := range []string{"href", "projectcode", "buyerperson", "buyertel", "budget", "bidopentime", "agency", "projectscope", "winnerperson", "winnertel", "bidendtime", "district", "signendtime", "buyeraddr", "filetext"} {
  629. // selectMap[key] = 1
  630. //}
  631. }
  632. if checkCount == -1 && len(scd.SelectIds) > 500 {
  633. scd.SelectIds = scd.SelectIds[:500]
  634. }
  635. pool := make(chan bool, 10)
  636. wait := &sync.WaitGroup{}
  637. var lock sync.Mutex
  638. returnLsit := make([]map[string]interface{}, 0, len(scd.SelectIds))
  639. for _, v := range SplitArray(scd.SelectIds, 200) {
  640. pool <- true
  641. wait.Add(1)
  642. go func(arr []string) error {
  643. defer func() {
  644. wait.Done()
  645. <-pool
  646. }()
  647. //var queryIds []interface{}
  648. //for _, idStr := range arr {
  649. // queryIds = append(queryIds, mg.StringTOBsonId(idStr))
  650. //}
  651. query := fmt.Sprintf(`{"query":{"bool":{"must":[{"terms":{"id":["%s"]}}]}},"_source": [%s],"size":%d}`, strings.Join(arr, "\",\""), bidField, len(arr))
  652. log.Println("数据流量包 es count 信息查询:", query)
  653. data := *elastic.Get(INDEX, TYPE, query)
  654. if data != nil && len(data) > 0 {
  655. for _, bv := range data {
  656. bv["_id"] = mg.BsonIdToSId(bv["_id"])
  657. detail, _ := bv["detail"].(string)
  658. if detail != "" {
  659. bv["detail"] = contentfilterReg.ReplaceAllString(detail, "")
  660. }
  661. lock.Lock()
  662. returnLsit = append(returnLsit, bv)
  663. lock.Unlock()
  664. }
  665. }
  666. return nil
  667. }(v)
  668. }
  669. wait.Wait()
  670. if len(returnLsit) == checkCount || checkCount == -1 {
  671. return &returnLsit, nil
  672. } else {
  673. return nil, fmt.Errorf("选择数据导出异常 数据量期望%d条,实际查询%d条", checkCount, len(returnLsit))
  674. }
  675. }
  676. // SplitArray 分割数组
  677. func SplitArray(arr []string, num int64) [][]string {
  678. max := int64(len(arr))
  679. //判断数组大小是否小于等于指定分割大小的值,是则把原数组放入二维数组返回
  680. if max <= num {
  681. return [][]string{arr}
  682. }
  683. //获取应该数组分割为多少份
  684. var quantity int64
  685. if max%num == 0 {
  686. quantity = max / num
  687. } else {
  688. quantity = (max / num) + 1
  689. }
  690. //声明分割好的二维数组
  691. var segments = make([][]string, 0)
  692. //声明分割数组的截止下标
  693. var start, end, i int64
  694. for i = 1; i <= quantity; i++ {
  695. end = i * num
  696. if i != quantity {
  697. segments = append(segments, arr[start:end])
  698. } else {
  699. segments = append(segments, arr[start:])
  700. }
  701. start = i * num
  702. }
  703. return segments
  704. }
  705. func GetDataExportIds(elasticAddress string, scd *SieveCondition, checkCount int) ([]string, error) {
  706. defer qutil.Catch()
  707. if scd == nil {
  708. return nil, errors.New("GetDataExportIds-未获取到查询信息")
  709. }
  710. if scd.SelectIds != nil {
  711. return scd.SelectIds, nil
  712. }
  713. var qstr string
  714. if scd.SearchMode == SearchModeAccurate {
  715. //获取查询语句
  716. qstr = getDataExportSql(scd)
  717. log.Printf("GetDataExportIds-%s-sql:%s\n", scd.Id, qstr)
  718. }
  719. //超级搜索一致的检索(防止数据导出和超级搜索数据量不一致)
  720. // 依据用户选择的搜索模式和搜索范围进行匹配,即不限制只能匹配标题,且不限制最多展示100条、针对输入的单个关键词分词后需要都包含
  721. if scd.Comeinfrom == "supersearchPage" && (len(scd.Keyword) != 0 || len(scd.Industry) != 0) && len(scd.SelectIds) == 0 && scd.SearchMode == SearchModeFuzzy {
  722. if len(scd.Keyword) != 0 {
  723. searchTextSize := 0
  724. // 关键词分词
  725. if len(scd.Keyword) > 0 {
  726. searchTextSize = len([]rune(scd.Keyword[0].Keyword))
  727. }
  728. if searchTextSize > 0 {
  729. if secondKWS := jy.HttpEs(scd.Keyword[0].Keyword, "ik_smart", elasticAddress); secondKWS != "" {
  730. scd.Keyword[0].Keyword = jy.KeywordsProcessing(strings.ReplaceAll(secondKWS, "+", " "), " ")
  731. }
  732. }
  733. // 附加词分词
  734. for i := 0; i < len(scd.Keyword[0].Appended); i++ {
  735. appendTextSize := 0
  736. if len(scd.Keyword[0].Appended[i]) > 0 {
  737. appendTextSize = len([]rune(scd.Keyword[0].Appended[i]))
  738. }
  739. if appendTextSize > 0 {
  740. if secondKWS := jy.HttpEs(scd.Keyword[0].Appended[i], "ik_smart", elasticAddress); secondKWS != "" {
  741. scd.Keyword[0].Appended[i] = jy.KeywordsProcessing(strings.ReplaceAll(secondKWS, "+", " "), " ")
  742. }
  743. }
  744. }
  745. }
  746. qstr = getDataExportSql(scd)
  747. log.Printf("GetDataExportIds-%s-分词查询-sql:%s\n", scd.Id, qstr)
  748. }
  749. res := doSearchByBatch(qstr, "1", checkCount, fmt.Sprintf("%s-%s", "GetDataExportSearchResult", scd.Id))
  750. //获取信息id
  751. idArr := make([]string, 0, 0)
  752. for _, v := range res {
  753. if id := qutil.ObjToString(v["_id"]); id != "" {
  754. idArr = append(idArr, id)
  755. }
  756. }
  757. if checkCount != len(idArr) {
  758. return nil, fmt.Errorf("GetDataExportIds-%s-数据总量校验异常,期望:%d,实际:%d", scd.Id, checkCount, len(res))
  759. }
  760. return idArr, nil
  761. }
  762. // GetDataExportSearchResult 获取数据导出内容
  763. // entmg 高级字段包查询企业电话邮箱等字段
  764. // checkCount -1 预览500条
  765. func GetDataExportSearchResult(elasticAddress string, scd *SieveCondition, dataType string, checkCount int) (*[]map[string]interface{}, error) {
  766. defer qutil.Catch()
  767. if scd == nil {
  768. return nil, errors.New("GetDataExportSearchResult-未获取到查询信息")
  769. }
  770. if scd.SelectIds != nil {
  771. idSelectDates, idSelectErr := GetDataExportSelectResult(scd, dataType, checkCount)
  772. if idSelectErr != nil {
  773. return nil, idSelectErr
  774. }
  775. GetDataExportMatchKey(scd, idSelectDates)
  776. return idSelectDates, idSelectErr
  777. }
  778. selectType := scd.SelectType
  779. var qstr string
  780. var res []map[string]interface{}
  781. if scd.SearchMode == SearchModeAccurate { // 搜索模式为精确查找
  782. //获取查询语句
  783. qstr = getDataExportSql(scd)
  784. log.Printf("GetDataExportSearchResult-%s-sql:%s\n", scd.Id, qstr)
  785. //数据导出数据查询
  786. res = doSearchByBatch(qstr, dataType, checkCount, fmt.Sprintf("%s-%s", "GetDataExportSearchResult", scd.Id))
  787. }
  788. //超级搜索一致的检索(防止数据导出和超级搜索数据量不一致)
  789. if scd.Comeinfrom == "supersearchPage" && (len(scd.Keyword) != 0 || len(scd.Industry) != 0) && len(scd.SelectIds) == 0 && scd.SearchMode == SearchModeFuzzy {
  790. if len(scd.Keyword) != 0 {
  791. searchTextSize := 0
  792. // 关键词分词
  793. if len(scd.Keyword) > 0 {
  794. searchTextSize = len([]rune(scd.Keyword[0].Keyword))
  795. }
  796. if searchTextSize > 0 {
  797. if secondKWS := jy.HttpEs(scd.Keyword[0].Keyword, "ik_smart", elasticAddress); secondKWS != "" {
  798. scd.Keyword[0].Keyword = jy.KeywordsProcessing(strings.ReplaceAll(secondKWS, "+", " "), " ")
  799. }
  800. }
  801. // 附加词分词
  802. for i := 0; i < len(scd.Keyword[0].Appended); i++ {
  803. appendTextSize := 0
  804. if len(scd.Keyword[0].Appended[i]) > 0 {
  805. appendTextSize = len([]rune(scd.Keyword[0].Appended[i]))
  806. }
  807. if appendTextSize > 0 {
  808. if secondKWS := jy.HttpEs(scd.Keyword[0].Appended[i], "ik_smart", elasticAddress); secondKWS != "" {
  809. scd.Keyword[0].Appended[i] = jy.KeywordsProcessing(strings.ReplaceAll(secondKWS, "+", " "), " ")
  810. }
  811. }
  812. }
  813. }
  814. qstr = getDataExportSql(scd)
  815. log.Printf("GetDataExportSearchResult-%s-分词查询-sql:%s\n", scd.Id, qstr)
  816. res = doSearchByBatch(qstr, dataType, checkCount, fmt.Sprintf("%s-%s", "GetDataExportSearchResult", scd.Id))
  817. }
  818. //校验数量
  819. if checkCount > len(res) && checkCount != -1 {
  820. return nil, fmt.Errorf("GetDataExportSearchResult-%s-数据总量校验异常,期望:%d,实际:%d", scd.Id, checkCount, len(res))
  821. }
  822. if selectType != scd.SelectType {
  823. scd.SelectType = selectType
  824. }
  825. GetDataExportMatchKey(scd, &res)
  826. return &res, nil
  827. }
  828. func doSearchByBatch(query, dataType string, searchCount int, flag string) (res []map[string]interface{}) {
  829. if searchCount > onceSearchCount { //分批次查询
  830. batchNum := qutil.IntAll(math.Ceil(float64(searchCount) / float64(onceSearchCount)))
  831. var searchWaitGroup = &sync.WaitGroup{}
  832. var lock sync.Mutex
  833. for n := 0; n < batchNum; n++ {
  834. searchWaitGroup.Add(1)
  835. searchPool <- true
  836. go func(start int) {
  837. defer func() {
  838. searchWaitGroup.Done()
  839. <-searchPool
  840. }()
  841. checkNum, checkOk := onceSearchCount, false
  842. if start == (batchNum - 1) {
  843. if searchCount%onceSearchCount != 0 {
  844. checkNum = searchCount % onceSearchCount
  845. }
  846. }
  847. var tmp *[]map[string]interface{}
  848. for i := 0; i < 3; i++ {
  849. tmp = doSearch(query, start*onceSearchCount, onceSearchCount, dataType)
  850. if tmp != nil && (len(*tmp) == checkNum) { //校验数据量是否够
  851. checkOk = true
  852. break
  853. }
  854. }
  855. if tmp == nil {
  856. log.Printf("%s-第%d页数据查询结果为空\n", flag, start+1)
  857. return
  858. }
  859. if checkOk {
  860. log.Printf("%s-第%d页数据加载完成,共%d条\n", flag, start+1, len(*tmp))
  861. } else {
  862. log.Printf("%s-第%d页数据加载异常,共%d条,预期%d条\n", flag, start+1, len(*tmp), checkNum)
  863. }
  864. lock.Lock()
  865. res = append(res, *tmp...)
  866. lock.Unlock()
  867. }(n)
  868. }
  869. searchWaitGroup.Wait()
  870. log.Printf("%s-分批次加载数据总量为%d\n", flag, len(res))
  871. } else {
  872. queryCount := qutil.If(searchCount == -1, onceSearchCount, searchCount).(int)
  873. searchPool <- true
  874. tmp := doSearch(query, 0, queryCount, dataType)
  875. <-searchPool
  876. if tmp == nil || len(*tmp) == 0 {
  877. log.Printf("%s-一次性加载数据异常\n", flag)
  878. } else {
  879. res = *tmp
  880. log.Printf("%s-一次性加载数据总量为%d\n", flag, len(res))
  881. }
  882. }
  883. return
  884. }
  885. func FormatExportData(data *[]map[string]interface{}, webdomain string, dataType string, encry ...bool) *[]map[string]interface{} {
  886. //格式化输出
  887. isEncry := false
  888. if len(encry) > 0 {
  889. isEncry = true
  890. }
  891. var entCacheMap = map[string]map[string]interface{}{}
  892. for index := 0; index < len(*data); index++ {
  893. v := (*data)[index]
  894. //有中标企业 且 高级字段查询
  895. if dataType == "2" {
  896. //查询企业公示 法人 公司电话 公司邮箱地址
  897. entidlist, ok := v["entidlist"].([]interface{})
  898. if ok && len(entidlist) > 0 {
  899. var winnerMaps []map[string]interface{}
  900. for _, entIdObj := range entidlist {
  901. entId := qutil.ObjToString(entIdObj)
  902. if entId == "" {
  903. continue
  904. }
  905. if entCacheMap[entId] != nil {
  906. winnerMaps = append(winnerMaps, entCacheMap[entId])
  907. } else if entDetail := elastic.Get("qyxy", "qyxy", fmt.Sprintf(`{"query":{"bool":{"must":[{"term":{"id":"%s"}}]}},"size":1,"_source":["company_name","company_email","company_phone","legal_person"]}`, entId)); entDetail != nil && len(*entDetail) > 0 {
  908. thisEntMap := map[string]interface{}{}
  909. legal_person := ""
  910. if (*entDetail)[0]["legal_person"] != nil {
  911. legal_person = (*entDetail)[0]["legal_person"].(string)
  912. if isEncry {
  913. var xx = "*"
  914. switch len([]rune(legal_person)) {
  915. case 3:
  916. xx = "**"
  917. case 4:
  918. xx = "***"
  919. }
  920. legal_person = string([]rune(legal_person)[:1]) + xx
  921. }
  922. }
  923. company_phone := ""
  924. if (*entDetail)[0]["company_phone"] != nil {
  925. company_phone = (*entDetail)[0]["company_phone"].(string)
  926. if isEncry {
  927. if len([]rune(company_phone)) > 7 {
  928. company_phone = company_phone[:7] + "****"
  929. } else {
  930. company_phone = "****"
  931. }
  932. }
  933. }
  934. company_email := ""
  935. if (*entDetail)[0]["company_email"] != nil && (*entDetail)[0]["company_email"] != "无" {
  936. company_email = (*entDetail)[0]["company_email"].(string)
  937. if isEncry {
  938. if len(strings.Split(company_email, "@")) > 1 {
  939. company_email = "******" + "@" + strings.Split(company_email, "@")[1]
  940. }
  941. }
  942. }
  943. company_name := ""
  944. if (*entDetail)[0]["company_name"] != nil {
  945. company_name = (*entDetail)[0]["company_name"].(string)
  946. }
  947. thisEntMap["legal_person"] = legal_person
  948. thisEntMap["company_phone"] = company_phone
  949. thisEntMap["company_email"] = company_email
  950. thisEntMap["company_name"] = company_name
  951. entCacheMap[entId] = thisEntMap
  952. winnerMaps = append(winnerMaps, thisEntMap)
  953. }
  954. }
  955. if len(winnerMaps) > 0 {
  956. v["winnerMaps"] = winnerMaps
  957. }
  958. }
  959. delete(v, "entidlist")
  960. }
  961. //====================字段补漏=========================
  962. if v["toptype"] == "结果" && dataType == "2" && !(v["agency"] != nil && v["budget"] != nil && v["buyerperson"] != nil && v["buyertel"] != nil) {
  963. r := elastic.Get("projectset", "projectset", fmt.Sprintf(`{"query":{"term":{"list.infoid":"%s"}},"_source": ["list"]}`, v["_id"]))
  964. if r != nil && len(*r) > 0 {
  965. MsgList := (*r)[0]["list"]
  966. if MsgList != nil {
  967. list := qutil.ObjArrToMapArr(MsgList.([]interface{}))
  968. for _, vv := range list {
  969. if vv["subtype"] == "招标" {
  970. if v["agency"] == nil && vv["agency"] != nil {
  971. v["agency"] = vv["agency"]
  972. }
  973. if v["budget"] == nil && vv["budget"] != nil {
  974. v["budget"] = vv["budget"]
  975. }
  976. if v["buyerperson"] == nil && vv["buyerperson"] != nil {
  977. v["buyerperson"] = vv["buyerperson"]
  978. }
  979. if v["buyertel"] == nil && vv["buyertel"] != nil {
  980. v["buyertel"] = vv["buyertel"]
  981. }
  982. break
  983. }
  984. }
  985. }
  986. }
  987. }
  988. if v["area"] == "A" {
  989. v["area"] = "全国"
  990. }
  991. if v["bidamount"] != nil {
  992. v["bidamount"] = formatFloat(qutil.Float64All(v["bidamount"]))
  993. }
  994. if v["budget"] != nil {
  995. v["budget"] = formatFloat(qutil.Float64All(v["budget"]))
  996. }
  997. if v["publishtime"] != nil {
  998. date := v["publishtime"]
  999. v["publishtime"] = FormatDateWithObj(&date, Date_Short_Layout)
  1000. }
  1001. if v["bidopentime"] != nil {
  1002. date := v["bidopentime"]
  1003. v["bidopentime"] = FormatDateWithObj(&date, Date_Short_Layout)
  1004. }
  1005. if qutil.IntAll(v["signendtime"]) != 0 {
  1006. date := v["signendtime"]
  1007. v["signendtime"] = FormatDateWithObj(&date, Date_Short_Layout)
  1008. }
  1009. if v["bidendtime"] != nil {
  1010. date := v["bidendtime"]
  1011. v["bidendtime"] = FormatDateWithObj(&date, Date_Short_Layout)
  1012. }
  1013. if v["_id"] != nil {
  1014. encodeId := CommonEncodeArticle("content", v["_id"].(string))
  1015. v["url"] = webdomain + "/article/content/" + encodeId + ".html"
  1016. v["url_jump"] = webdomain + "/front/reloadTo/article/content/" + encodeId + ".html"
  1017. }
  1018. if v["currency"] == "" || v["currency"] == nil {
  1019. v["currency"] = "人民币"
  1020. }
  1021. if isEncry {
  1022. if v["projectscope"] != "" && v["projectscope"] != nil {
  1023. str := ClearHtml.ReplaceAllString(v["projectscope"].(string), "")
  1024. str = ClearOther.ReplaceAllString(str, "")
  1025. str = strings.Replace(str, " ", "", -1)
  1026. if len([]rune(str)) > 100 {
  1027. str = qutil.SubString(str, 0, 100) + "..."
  1028. }
  1029. v["projectscope"] = str
  1030. }
  1031. if v["detail"] != "" && v["detail"] != nil {
  1032. str := ClearHtml.ReplaceAllString(v["detail"].(string), "")
  1033. str = ClearOther.ReplaceAllString(str, "")
  1034. str = strings.Replace(str, " ", "", -1)
  1035. if len([]rune(str)) > 100 {
  1036. str = qutil.SubString(str, 0, 100) + "..."
  1037. }
  1038. v["detail"] = str
  1039. }
  1040. if v["title"] != "" && v["title"] != nil {
  1041. str := ClearHtml.ReplaceAllString(v["title"].(string), "")
  1042. str = ClearOther.ReplaceAllString(str, "")
  1043. str = strings.Replace(str, " ", "", -1)
  1044. if len([]rune(str)) > 100 {
  1045. str = qutil.SubString(str, 0, 100) + "..."
  1046. }
  1047. v["title"] = str
  1048. }
  1049. }
  1050. if v["subtype"] == nil && v["toptype"] != nil {
  1051. v["subtype"] = v["toptype"]
  1052. }
  1053. }
  1054. return data
  1055. }
  1056. // 保留到0.01分
  1057. func formatFloat(value float64) string {
  1058. str := strings.TrimRight(fmt.Sprintf("%.7f", value*10000/100000000), "0")
  1059. if str[len(str)-1:] == "." {
  1060. return str[:len(str)-1]
  1061. }
  1062. return str
  1063. }
  1064. func doSearch(sql string, start, count int, dataType string) *[]map[string]interface{} {
  1065. if sql != "" {
  1066. //筛选字段
  1067. if dataType != "" {
  1068. dataexport_field := `"_id","title","detail","area","city","publishtime","projectname","buyer","s_winner","bidamount","subtype","toptype","filetext","purchasing"`
  1069. if dataType == "2" {
  1070. dataexport_field += `,"href","projectcode","buyerperson","buyertel","budget","bidopentime","agency","projectscope","winnerperson","winnertel","bidendtime","district","signendtime","buyeraddr","buyerclass","s_topscopeclass","entidlist"`
  1071. }
  1072. sql = sql[:len(sql)-1] + `,"_source":[` + dataexport_field + "]}"
  1073. }
  1074. //分页排序
  1075. sql = sql[:len(sql)-1] + `,"sort": {"dataweight": "desc","publishtime":"desc","id":"desc"},"from":` + strconv.Itoa(start) + `,"size":` + strconv.Itoa(count) + "}"
  1076. }
  1077. log.Println("doSearch", sql)
  1078. return elastic.Get(INDEX, TYPE, sql)
  1079. }
  1080. func getKeyWordArrFromDbResult(k interface{}) (arr []KeyWord) {
  1081. if k == nil {
  1082. return
  1083. }
  1084. kArr := k.([]interface{})
  1085. for _, v := range kArr {
  1086. kw := KeyWord{}
  1087. b, e := json.Marshal(v)
  1088. if e != nil {
  1089. log.Println(e.Error())
  1090. }
  1091. json.Unmarshal(b, &kw)
  1092. arr = append(arr, kw)
  1093. }
  1094. return
  1095. }
  1096. func getStringArrFromDbResult(c interface{}) (arr []string) {
  1097. if c != nil {
  1098. cArr := c.([]interface{})
  1099. arr = qutil.ObjArrToStringArr(cArr)
  1100. }
  1101. return
  1102. }
  1103. // 获取结果,空字段最少的数据
  1104. func ScreenData(arr *[]map[string]interface{}, dataType string, resultNum int, kws []KeyWord) (res []map[string]interface{}) {
  1105. AllMap := map[int][]map[string]interface{}{}
  1106. NoKwsMap := map[int][]map[string]interface{}{}
  1107. lastNum := resultNum
  1108. for _, v := range *arr {
  1109. emptyNum := countOfTheEmpty(v, dataType)
  1110. if emptyNum == -1 {
  1111. continue
  1112. }
  1113. if len(kws) > 0 && kws[0].Keyword != "" {
  1114. var kwsFlag = true
  1115. for _, vk := range kws {
  1116. if strings.Contains(qutil.ObjToString(v["title"]), strings.Replace(vk.Keyword, "+", "", -1)) {
  1117. kwsFlag = false
  1118. continue
  1119. }
  1120. }
  1121. if kwsFlag {
  1122. if NoKwsMap[emptyNum] == nil {
  1123. NoKwsMap[emptyNum] = []map[string]interface{}{v}
  1124. } else {
  1125. NoKwsMap[emptyNum] = append(NoKwsMap[emptyNum], v)
  1126. }
  1127. continue
  1128. }
  1129. }
  1130. if AllMap[emptyNum] == nil {
  1131. AllMap[emptyNum] = []map[string]interface{}{v}
  1132. continue
  1133. }
  1134. AllMap[emptyNum] = append(AllMap[emptyNum], v)
  1135. }
  1136. //获取key
  1137. keys := []int{}
  1138. for k, _ := range AllMap {
  1139. keys = append(keys, k)
  1140. }
  1141. sort.Ints(keys)
  1142. //选取结果
  1143. for _, v := range keys {
  1144. if len(AllMap[v]) >= resultNum {
  1145. return append(res, AllMap[v][:resultNum]...)
  1146. } else {
  1147. resultNum = resultNum - len(AllMap[v])
  1148. tmp := append(res, AllMap[v][:len(AllMap[v])]...)
  1149. res = tmp
  1150. }
  1151. }
  1152. if len(res) < lastNum {
  1153. resultNum = lastNum - len(res)
  1154. //获取key
  1155. Nokeys := []int{}
  1156. for k, _ := range NoKwsMap {
  1157. Nokeys = append(Nokeys, k)
  1158. }
  1159. sort.Ints(Nokeys)
  1160. log.Println("没关键词的空字段数量", Nokeys)
  1161. //选取结果
  1162. for _, v := range Nokeys {
  1163. if len(NoKwsMap[v]) >= resultNum {
  1164. return append(res, NoKwsMap[v][:resultNum]...)
  1165. } else {
  1166. resultNum = resultNum - len(NoKwsMap[v])
  1167. tmp := append(res, NoKwsMap[v][:len(NoKwsMap[v])]...)
  1168. res = tmp
  1169. }
  1170. }
  1171. }
  1172. return res
  1173. }
  1174. func countOfTheEmpty(m map[string]interface{}, dataType string) int {
  1175. MsgType := m["subtype"]
  1176. // if MsgType == "拟建" {
  1177. // return -1
  1178. // }
  1179. //计算空字段数量
  1180. var count int = 0
  1181. //高级字段包
  1182. if dataType == "2" {
  1183. if m["href"] == "" || m["href"] == nil {
  1184. count++
  1185. }
  1186. if m["projectcode"] == "" || m["projectcode"] == nil {
  1187. count++
  1188. }
  1189. if m["buyerperson"] == "" || m["buyerperson"] == nil {
  1190. count++
  1191. }
  1192. if m["buyertel"] == "" || m["buyertel"] == nil {
  1193. count++
  1194. }
  1195. if m["budget"] == "" || m["budget"] == nil {
  1196. count++
  1197. }
  1198. if m["bidopentime"] == "" || m["bidopentime"] == nil {
  1199. count++
  1200. }
  1201. if m["agency"] == "" || m["agency"] == nil {
  1202. count++
  1203. }
  1204. if m["projectscope"] == "" || m["projectscope"] == nil {
  1205. count++
  1206. }
  1207. }
  1208. if m["city"] == "" || m["city"] == nil {
  1209. count++
  1210. }
  1211. if m["publishtime"] == "" || m["publishtime"] == nil {
  1212. count++
  1213. }
  1214. if m["projectname"] == "" || m["projectname"] == nil {
  1215. count++
  1216. }
  1217. if m["buyer"] == "" || m["buyer"] == nil {
  1218. count++
  1219. }
  1220. if m["s_winner"] == "" || m["s_winner"] == nil {
  1221. if MsgType != "招标" {
  1222. count++
  1223. }
  1224. }
  1225. if m["bidamount"] == "" || m["bidamount"] == nil {
  1226. if MsgType != "招标" {
  1227. count++
  1228. }
  1229. }
  1230. if m["subtype"] == "" || m["subtype"] == nil {
  1231. count++
  1232. }
  1233. return count
  1234. }