dataexport.go 49 KB

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