dataexport.go 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401
  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 (
  624. count int64
  625. lock sync.Mutex
  626. )
  627. pool := make(chan bool, 10)
  628. wait := &sync.WaitGroup{}
  629. for _, i2 := range SplitArray(ids, 200) {
  630. pool <- true
  631. wait.Add(1)
  632. go func(arr []string) {
  633. defer func() {
  634. wait.Done()
  635. <-pool
  636. }()
  637. lenNum := int64(len(arr))
  638. var (
  639. queryIds []interface{}
  640. num1, num2 int64
  641. err error
  642. )
  643. for _, idStr := range arr {
  644. queryIds = append(queryIds, mg.StringTOBsonId(idStr))
  645. }
  646. num1, err = sess.DB(biddingName).C("bidding").Find(map[string]interface{}{"_id": map[string]interface{}{
  647. "$in": queryIds,
  648. }}).Count()
  649. if err == nil {
  650. if num1 == lenNum {
  651. lock.Lock()
  652. count += num1
  653. lock.Unlock()
  654. return
  655. }
  656. num2, err = sess.DB(biddingName).C("bidding_back").Find(map[string]interface{}{"_id": map[string]interface{}{
  657. "$in": queryIds,
  658. }}).Count()
  659. if err == nil {
  660. lock.Lock()
  661. count += qutil.If(num2+num1 >= lenNum, lenNum, num2+num1).(int64)
  662. lock.Unlock()
  663. }
  664. }
  665. }(i2)
  666. }
  667. wait.Wait()
  668. return qutil.If(count > 0, count, -2).(int64)
  669. }
  670. func GetDataExportSelectResultFromEs(bidding mg.MongodbSim, biddingName string, scd *SieveCondition, dataType string, checkCount int) (*[]map[string]interface{}, error) {
  671. bidField := `"_id", "title", "detail", "area", "city", "publishtime", "projectname", "buyer", "s_winner", "bidamount", "subtype", "toptype", "filetext", "purchasing"`
  672. //selectMap := map[string]interface{}{
  673. // "_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,
  674. //}
  675. if dataType == "2" {
  676. bidField = bidField + `,"href", "projectcode", "buyerperson", "buyertel", "budget", "bidopentime", "agency", "projectscope", "winnerperson", "winnertel", "bidendtime", "district", "signendtime", "buyeraddr","buyerclass","s_topscopeclass","entidlist"`
  677. //for _, key := range []string{"href", "projectcode", "buyerperson", "buyertel", "budget", "bidopentime", "agency", "projectscope", "winnerperson", "winnertel", "bidendtime", "district", "signendtime", "buyeraddr", "filetext"} {
  678. // selectMap[key] = 1
  679. //}
  680. }
  681. if checkCount == -1 && len(scd.SelectIds) > 500 {
  682. scd.SelectIds = scd.SelectIds[:500]
  683. }
  684. pool := make(chan bool, 10)
  685. wait := &sync.WaitGroup{}
  686. var lock sync.Mutex
  687. returnLsit := make([]map[string]interface{}, 0, len(scd.SelectIds))
  688. for _, v := range SplitArray(scd.SelectIds, 200) {
  689. pool <- true
  690. wait.Add(1)
  691. go func(arr []string) error {
  692. defer func() {
  693. wait.Done()
  694. <-pool
  695. }()
  696. query := fmt.Sprintf(`{"query":{"bool":{"must":[{"terms":{"id":["%s"]}}]}},"_source": [%s],"size":%d}`, strings.Join(arr, "\",\""), bidField, len(arr))
  697. log.Println("GetDataExportSelectResultFromEs 数据流量包 es count 信息查询:", query)
  698. data := *elastic.Get(INDEX, TYPE, query)
  699. if data != nil && len(data) > 0 {
  700. for _, bv := range data {
  701. bv["_id"] = mg.BsonIdToSId(bv["_id"])
  702. detail, _ := bv["detail"].(string)
  703. if detail != "" {
  704. bv["detail"] = contentfilterReg.ReplaceAllString(detail, "")
  705. }
  706. lock.Lock()
  707. returnLsit = append(returnLsit, bv)
  708. lock.Unlock()
  709. }
  710. }
  711. return nil
  712. }(v)
  713. }
  714. wait.Wait()
  715. if len(returnLsit) == checkCount || checkCount == -1 {
  716. return &returnLsit, nil
  717. } else {
  718. return nil, fmt.Errorf("GetDataExportSelectResultFromEs 选择数据导出异常 数据量期望%d条,实际查询%d条", checkCount, len(returnLsit))
  719. }
  720. }
  721. func GetDataExportSelectResultFromMongoDb(bidding mg.MongodbSim, biddingName string, scd *SieveCondition, dataType string, checkCount int) (*[]map[string]interface{}, error) {
  722. sess := bidding.GetMgoConn()
  723. defer bidding.DestoryMongoConn(sess)
  724. selectMap := map[string]interface{}{
  725. "_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,
  726. }
  727. if dataType == "2" {
  728. for _, key := range []string{"href", "projectcode", "buyerperson", "buyertel", "budget", "bidopentime", "agency", "projectscope", "winnerperson", "winnertel", "bidendtime", "district", "signendtime", "buyeraddr", "filetext", "buyerclass", "s_topscopeclass", "entidlist"} {
  729. selectMap[key] = 1
  730. }
  731. }
  732. if checkCount == -1 && len(scd.SelectIds) > 500 {
  733. scd.SelectIds = scd.SelectIds[:500]
  734. }
  735. pool := make(chan bool, 10)
  736. wait := &sync.WaitGroup{}
  737. var lock sync.Mutex
  738. returnLsit := make([]map[string]interface{}, 0, len(scd.SelectIds))
  739. for _, v := range SplitArray(scd.SelectIds, 200) {
  740. pool <- true
  741. wait.Add(1)
  742. go func(arr []string) error {
  743. defer func() {
  744. wait.Done()
  745. <-pool
  746. }()
  747. var queryIds []interface{}
  748. for _, idStr := range arr {
  749. queryIds = append(queryIds, mg.StringTOBsonId(idStr))
  750. }
  751. iter := sess.DB(biddingName).C("bidding").Select(selectMap).Find(map[string]interface{}{"_id": map[string]interface{}{
  752. "$in": queryIds,
  753. }}).Iter()
  754. for m := make(map[string]interface{}); iter.Next(&m); {
  755. m["_id"] = mg.BsonIdToSId(m["_id"])
  756. detail, _ := m["detail"].(string)
  757. if detail != "" {
  758. m["detail"] = contentfilterReg.ReplaceAllString(detail, "")
  759. }
  760. lock.Lock()
  761. returnLsit = append(returnLsit, m)
  762. lock.Unlock()
  763. m = make(map[string]interface{})
  764. }
  765. iter_back := sess.DB(biddingName).C("bidding_back").Select(selectMap).Find(map[string]interface{}{"_id": map[string]interface{}{
  766. "$in": queryIds,
  767. }}).Iter()
  768. for m := make(map[string]interface{}); iter_back.Next(&m); {
  769. m["_id"] = mg.BsonIdToSId(m["_id"])
  770. detail, _ := m["detail"].(string)
  771. if detail != "" {
  772. m["detail"] = contentfilterReg.ReplaceAllString(detail, "")
  773. }
  774. lock.Lock()
  775. returnLsit = append(returnLsit, m)
  776. lock.Unlock()
  777. m = make(map[string]interface{})
  778. }
  779. return nil
  780. }(v)
  781. }
  782. wait.Wait()
  783. if len(returnLsit) == checkCount || checkCount == -1 {
  784. return &returnLsit, nil
  785. } else {
  786. return nil, fmt.Errorf("GetDataExportSelectResultFromMongoDb 选择数据导出异常 数据量期望%d条,实际查询%d条", checkCount, len(returnLsit))
  787. }
  788. }
  789. // SplitArray 分割数组
  790. func SplitArray(arr []string, num int64) [][]string {
  791. max := int64(len(arr))
  792. //判断数组大小是否小于等于指定分割大小的值,是则把原数组放入二维数组返回
  793. if max <= num {
  794. return [][]string{arr}
  795. }
  796. //获取应该数组分割为多少份
  797. var quantity int64
  798. if max%num == 0 {
  799. quantity = max / num
  800. } else {
  801. quantity = (max / num) + 1
  802. }
  803. //声明分割好的二维数组
  804. var segments = make([][]string, 0)
  805. //声明分割数组的截止下标
  806. var start, end, i int64
  807. for i = 1; i <= quantity; i++ {
  808. end = i * num
  809. if i != quantity {
  810. segments = append(segments, arr[start:end])
  811. } else {
  812. segments = append(segments, arr[start:])
  813. }
  814. start = i * num
  815. }
  816. return segments
  817. }
  818. func GetDataExportIds(elasticAddress string, scd *SieveCondition, checkCount int) ([]string, error) {
  819. defer qutil.Catch()
  820. if scd == nil {
  821. return nil, errors.New("GetDataExportIds-未获取到查询信息")
  822. }
  823. if scd.SelectIds != nil {
  824. return scd.SelectIds, nil
  825. }
  826. var qstr string
  827. if scd.SearchMode == SearchModeAccurate {
  828. //获取查询语句
  829. qstr = getDataExportSql(scd)
  830. log.Printf("GetDataExportIds-%s-sql:%s\n", scd.Id, qstr)
  831. }
  832. //超级搜索一致的检索(防止数据导出和超级搜索数据量不一致)
  833. // 依据用户选择的搜索模式和搜索范围进行匹配,即不限制只能匹配标题,且不限制最多展示100条、针对输入的单个关键词分词后需要都包含
  834. if scd.Comeinfrom == "supersearchPage" && (len(scd.Keyword) != 0 || len(scd.Industry) != 0) && len(scd.SelectIds) == 0 && scd.SearchMode == SearchModeFuzzy {
  835. if len(scd.Keyword) != 0 {
  836. searchTextSize := 0
  837. // 关键词分词
  838. if len(scd.Keyword) > 0 {
  839. searchTextSize = len([]rune(scd.Keyword[0].Keyword))
  840. }
  841. if searchTextSize > 0 {
  842. if secondKWS := jy.HttpEs(scd.Keyword[0].Keyword, "ik_smart", elasticAddress); secondKWS != "" {
  843. scd.Keyword[0].Keyword = jy.KeywordsProcessing(strings.ReplaceAll(secondKWS, "+", " "), " ")
  844. }
  845. }
  846. // 附加词分词
  847. for i := 0; i < len(scd.Keyword[0].Appended); i++ {
  848. appendTextSize := 0
  849. if len(scd.Keyword[0].Appended[i]) > 0 {
  850. appendTextSize = len([]rune(scd.Keyword[0].Appended[i]))
  851. }
  852. if appendTextSize > 0 {
  853. if secondKWS := jy.HttpEs(scd.Keyword[0].Appended[i], "ik_smart", elasticAddress); secondKWS != "" {
  854. scd.Keyword[0].Appended[i] = jy.KeywordsProcessing(strings.ReplaceAll(secondKWS, "+", " "), " ")
  855. }
  856. }
  857. }
  858. }
  859. qstr = getDataExportSql(scd)
  860. log.Printf("GetDataExportIds-%s-分词查询-sql:%s\n", scd.Id, qstr)
  861. }
  862. res := doSearchByBatch(qstr, "1", checkCount, fmt.Sprintf("%s-%s", "GetDataExportSearchResult", scd.Id))
  863. //获取信息id
  864. idArr := make([]string, 0, 0)
  865. for _, v := range res {
  866. if id := qutil.ObjToString(v["_id"]); id != "" {
  867. idArr = append(idArr, id)
  868. }
  869. }
  870. if checkCount != len(idArr) {
  871. return nil, fmt.Errorf("GetDataExportIds-%s-数据总量校验异常,期望:%d,实际:%d", scd.Id, checkCount, len(res))
  872. }
  873. return idArr, nil
  874. }
  875. // GetDataExportSearchResult 获取数据导出内容
  876. // entmg 高级字段包查询企业电话邮箱等字段
  877. // checkCount -1 预览500条
  878. func GetDataExportSearchResult(bid mg.MongodbSim, bidMgoDBName, elasticAddress string, scd *SieveCondition, dataType string, checkCount int) (*[]map[string]interface{}, error) {
  879. defer qutil.Catch()
  880. if scd == nil {
  881. return nil, errors.New("GetDataExportSearchResult-未获取到查询信息")
  882. }
  883. if scd.SelectIds != nil {
  884. idSelectDates, idSelectErr := GetDataExportSelectResultFromMongoDb(bid, bidMgoDBName, scd, dataType, checkCount)
  885. if idSelectErr != nil {
  886. return nil, idSelectErr
  887. }
  888. GetDataExportMatchKey(scd, idSelectDates)
  889. return idSelectDates, idSelectErr
  890. }
  891. selectType := scd.SelectType
  892. var qstr string
  893. var res []map[string]interface{}
  894. if scd.SearchMode == SearchModeAccurate { // 搜索模式为精确查找
  895. //获取查询语句
  896. qstr = getDataExportSql(scd)
  897. log.Printf("GetDataExportSearchResult-%s-sql:%s\n", scd.Id, qstr)
  898. //数据导出数据查询
  899. res = doSearchByBatch(qstr, dataType, checkCount, fmt.Sprintf("%s-%s", "GetDataExportSearchResult", scd.Id))
  900. }
  901. //超级搜索一致的检索(防止数据导出和超级搜索数据量不一致)
  902. if scd.Comeinfrom == "supersearchPage" && (len(scd.Keyword) != 0 || len(scd.Industry) != 0) && len(scd.SelectIds) == 0 && scd.SearchMode == SearchModeFuzzy {
  903. if len(scd.Keyword) != 0 {
  904. searchTextSize := 0
  905. // 关键词分词
  906. if len(scd.Keyword) > 0 {
  907. searchTextSize = len([]rune(scd.Keyword[0].Keyword))
  908. }
  909. if searchTextSize > 0 {
  910. if secondKWS := jy.HttpEs(scd.Keyword[0].Keyword, "ik_smart", elasticAddress); secondKWS != "" {
  911. scd.Keyword[0].Keyword = jy.KeywordsProcessing(strings.ReplaceAll(secondKWS, "+", " "), " ")
  912. }
  913. }
  914. // 附加词分词
  915. for i := 0; i < len(scd.Keyword[0].Appended); i++ {
  916. appendTextSize := 0
  917. if len(scd.Keyword[0].Appended[i]) > 0 {
  918. appendTextSize = len([]rune(scd.Keyword[0].Appended[i]))
  919. }
  920. if appendTextSize > 0 {
  921. if secondKWS := jy.HttpEs(scd.Keyword[0].Appended[i], "ik_smart", elasticAddress); secondKWS != "" {
  922. scd.Keyword[0].Appended[i] = jy.KeywordsProcessing(strings.ReplaceAll(secondKWS, "+", " "), " ")
  923. }
  924. }
  925. }
  926. }
  927. qstr = getDataExportSql(scd)
  928. log.Printf("GetDataExportSearchResult-%s-分词查询-sql:%s\n", scd.Id, qstr)
  929. res = doSearchByBatch(qstr, dataType, checkCount, fmt.Sprintf("%s-%s", "GetDataExportSearchResult", scd.Id))
  930. }
  931. //校验数量
  932. if checkCount != len(res) && checkCount != -1 {
  933. return nil, fmt.Errorf("GetDataExportSearchResult-%s-数据总量校验异常,期望:%d,实际:%d", scd.Id, checkCount, len(res))
  934. }
  935. if selectType != scd.SelectType {
  936. scd.SelectType = selectType
  937. }
  938. GetDataExportMatchKey(scd, &res)
  939. return &res, nil
  940. }
  941. func doSearchByBatch(query, dataType string, searchCount int, flag string) (res []map[string]interface{}) {
  942. if searchCount > onceSearchCount { //分批次查询
  943. batchNum := qutil.IntAll(math.Ceil(float64(searchCount) / float64(onceSearchCount)))
  944. var searchWaitGroup = &sync.WaitGroup{}
  945. var lock sync.Mutex
  946. for n := 0; n < batchNum; n++ {
  947. searchWaitGroup.Add(1)
  948. searchPool <- true
  949. go func(start int) {
  950. defer func() {
  951. searchWaitGroup.Done()
  952. <-searchPool
  953. }()
  954. checkNum, checkOk := onceSearchCount, false
  955. if start == (batchNum - 1) {
  956. if searchCount%onceSearchCount != 0 {
  957. checkNum = searchCount % onceSearchCount
  958. }
  959. }
  960. var tmp *[]map[string]interface{}
  961. for i := 0; i < 3; i++ {
  962. tmp = doSearch(query, start*onceSearchCount, onceSearchCount, dataType)
  963. if tmp != nil && (len(*tmp) == checkNum) { //校验数据量是否够
  964. checkOk = true
  965. break
  966. }
  967. }
  968. if tmp == nil {
  969. log.Printf("%s-第%d页数据查询结果为空\n", flag, start+1)
  970. return
  971. }
  972. if checkOk {
  973. log.Printf("%s-第%d页数据加载完成,共%d条\n", flag, start+1, len(*tmp))
  974. } else {
  975. log.Printf("%s-第%d页数据加载异常,共%d条,预期%d条\n", flag, start+1, len(*tmp), checkNum)
  976. }
  977. lock.Lock()
  978. res = append(res, *tmp...)
  979. lock.Unlock()
  980. }(n)
  981. }
  982. searchWaitGroup.Wait()
  983. log.Printf("%s-分批次加载数据总量为%d\n", flag, len(res))
  984. } else {
  985. queryCount := qutil.If(searchCount == -1, onceSearchCount, searchCount).(int)
  986. searchPool <- true
  987. tmp := doSearch(query, 0, queryCount, dataType)
  988. <-searchPool
  989. if tmp == nil || len(*tmp) == 0 {
  990. log.Printf("%s-一次性加载数据异常\n", flag)
  991. } else {
  992. res = *tmp
  993. log.Printf("%s-一次性加载数据总量为%d\n", flag, len(res))
  994. }
  995. }
  996. return
  997. }
  998. func FormatExportData(entmg mg.MongodbSim, data *[]map[string]interface{}, webdomain string, dataType string, encry ...bool) *[]map[string]interface{} {
  999. //格式化输出
  1000. isEncry := false
  1001. if len(encry) > 0 {
  1002. isEncry = true
  1003. }
  1004. var entCacheMap = map[string]map[string]interface{}{}
  1005. for index := 0; index < len(*data); index++ {
  1006. v := (*data)[index]
  1007. //有中标企业 且 高级字段查询
  1008. if dataType == "2" {
  1009. //查询企业公示 法人 公司电话 公司邮箱地址
  1010. entidlist, ok := v["entidlist"].([]interface{})
  1011. if ok && len(entidlist) > 0 {
  1012. var winnerMaps []map[string]interface{}
  1013. for _, entIdObj := range entidlist {
  1014. entId := qutil.ObjToString(entIdObj)
  1015. if entId == "" {
  1016. continue
  1017. }
  1018. if entCacheMap[entId] != nil {
  1019. winnerMaps = append(winnerMaps, entCacheMap[entId])
  1020. } 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 {
  1021. thisEntMap := map[string]interface{}{}
  1022. legal_person := ""
  1023. if (*entDetail)[0]["legal_person"] != nil {
  1024. legal_person = (*entDetail)[0]["legal_person"].(string)
  1025. if isEncry {
  1026. var xx = "*"
  1027. switch len([]rune(legal_person)) {
  1028. case 3:
  1029. xx = "**"
  1030. case 4:
  1031. xx = "***"
  1032. }
  1033. legal_person = string([]rune(legal_person)[:1]) + xx
  1034. }
  1035. }
  1036. company_phone := ""
  1037. if (*entDetail)[0]["company_phone"] != nil {
  1038. company_phone = (*entDetail)[0]["company_phone"].(string)
  1039. if isEncry {
  1040. if len([]rune(company_phone)) > 7 {
  1041. company_phone = company_phone[:7] + "****"
  1042. } else {
  1043. company_phone = "****"
  1044. }
  1045. }
  1046. }
  1047. company_email := ""
  1048. if (*entDetail)[0]["company_email"] != nil && (*entDetail)[0]["company_email"] != "无" {
  1049. company_email = (*entDetail)[0]["company_email"].(string)
  1050. if isEncry {
  1051. if len(strings.Split(company_email, "@")) > 1 {
  1052. company_email = "******" + "@" + strings.Split(company_email, "@")[1]
  1053. }
  1054. }
  1055. }
  1056. company_name := ""
  1057. if (*entDetail)[0]["company_name"] != nil {
  1058. company_name = (*entDetail)[0]["company_name"].(string)
  1059. }
  1060. thisEntMap["legal_person"] = legal_person
  1061. thisEntMap["company_phone"] = company_phone
  1062. thisEntMap["company_email"] = company_email
  1063. thisEntMap["company_name"] = company_name
  1064. entCacheMap[entId] = thisEntMap
  1065. winnerMaps = append(winnerMaps, thisEntMap)
  1066. }
  1067. }
  1068. if len(winnerMaps) > 0 {
  1069. v["winnerMaps"] = winnerMaps
  1070. }
  1071. }
  1072. delete(v, "entidlist")
  1073. }
  1074. //====================字段补漏=========================
  1075. if v["toptype"] == "结果" && dataType == "2" && !(v["agency"] != nil && v["budget"] != nil && v["buyerperson"] != nil && v["buyertel"] != nil) {
  1076. r := elastic.Get("projectset", "projectset", fmt.Sprintf(`{"query":{"term":{"list.infoid":"%s"}},"_source": ["list"]}`, v["_id"]))
  1077. if r != nil && len(*r) > 0 {
  1078. MsgList := (*r)[0]["list"]
  1079. if MsgList != nil {
  1080. list := qutil.ObjArrToMapArr(MsgList.([]interface{}))
  1081. for _, vv := range list {
  1082. if vv["subtype"] == "招标" {
  1083. if v["agency"] == nil && vv["agency"] != nil {
  1084. v["agency"] = vv["agency"]
  1085. }
  1086. if v["budget"] == nil && vv["budget"] != nil {
  1087. v["budget"] = vv["budget"]
  1088. }
  1089. if v["buyerperson"] == nil && vv["buyerperson"] != nil {
  1090. v["buyerperson"] = vv["buyerperson"]
  1091. }
  1092. if v["buyertel"] == nil && vv["buyertel"] != nil {
  1093. v["buyertel"] = vv["buyertel"]
  1094. }
  1095. break
  1096. }
  1097. }
  1098. }
  1099. }
  1100. }
  1101. if v["area"] == "A" {
  1102. v["area"] = "全国"
  1103. }
  1104. if v["bidamount"] != nil {
  1105. v["bidamount"] = formatFloat(qutil.Float64All(v["bidamount"]))
  1106. }
  1107. if v["budget"] != nil {
  1108. v["budget"] = formatFloat(qutil.Float64All(v["budget"]))
  1109. }
  1110. if v["publishtime"] != nil {
  1111. date := v["publishtime"]
  1112. v["publishtime"] = FormatDateWithObj(&date, Date_Short_Layout)
  1113. }
  1114. if v["bidopentime"] != nil {
  1115. date := v["bidopentime"]
  1116. v["bidopentime"] = FormatDateWithObj(&date, Date_Short_Layout)
  1117. }
  1118. if qutil.IntAll(v["signendtime"]) != 0 {
  1119. date := v["signendtime"]
  1120. v["signendtime"] = FormatDateWithObj(&date, Date_Short_Layout)
  1121. }
  1122. if v["bidendtime"] != nil {
  1123. date := v["bidendtime"]
  1124. v["bidendtime"] = FormatDateWithObj(&date, Date_Short_Layout)
  1125. }
  1126. if v["_id"] != nil {
  1127. encodeId := CommonEncodeArticle("content", v["_id"].(string))
  1128. v["url"] = webdomain + "/article/content/" + encodeId + ".html"
  1129. v["url_jump"] = webdomain + "/front/reloadTo/article/content/" + encodeId + ".html"
  1130. }
  1131. if v["currency"] == "" || v["currency"] == nil {
  1132. v["currency"] = "人民币"
  1133. }
  1134. if isEncry {
  1135. if v["projectscope"] != "" && v["projectscope"] != nil {
  1136. str := ClearHtml.ReplaceAllString(v["projectscope"].(string), "")
  1137. str = ClearOther.ReplaceAllString(str, "")
  1138. str = strings.Replace(str, " ", "", -1)
  1139. if len([]rune(str)) > 100 {
  1140. str = qutil.SubString(str, 0, 100) + "..."
  1141. }
  1142. v["projectscope"] = str
  1143. }
  1144. if v["detail"] != "" && v["detail"] != nil {
  1145. str := ClearHtml.ReplaceAllString(v["detail"].(string), "")
  1146. str = ClearOther.ReplaceAllString(str, "")
  1147. str = strings.Replace(str, " ", "", -1)
  1148. if len([]rune(str)) > 100 {
  1149. str = qutil.SubString(str, 0, 100) + "..."
  1150. }
  1151. v["detail"] = str
  1152. }
  1153. if v["title"] != "" && v["title"] != nil {
  1154. str := ClearHtml.ReplaceAllString(v["title"].(string), "")
  1155. str = ClearOther.ReplaceAllString(str, "")
  1156. str = strings.Replace(str, " ", "", -1)
  1157. if len([]rune(str)) > 100 {
  1158. str = qutil.SubString(str, 0, 100) + "..."
  1159. }
  1160. v["title"] = str
  1161. }
  1162. }
  1163. if v["subtype"] == nil && v["toptype"] != nil {
  1164. v["subtype"] = v["toptype"]
  1165. }
  1166. }
  1167. return data
  1168. }
  1169. // 保留到0.01分
  1170. func formatFloat(value float64) string {
  1171. str := strings.TrimRight(fmt.Sprintf("%.7f", value*10000/100000000), "0")
  1172. if str[len(str)-1:] == "." {
  1173. return str[:len(str)-1]
  1174. }
  1175. return str
  1176. }
  1177. func doSearch(sql string, start, count int, dataType string) *[]map[string]interface{} {
  1178. if sql != "" {
  1179. //筛选字段
  1180. if dataType != "" {
  1181. dataexport_field := `"_id","title","detail","area","city","publishtime","projectname","buyer","s_winner","bidamount","subtype","toptype","filetext","purchasing"`
  1182. if dataType == "2" {
  1183. dataexport_field += `,"href","projectcode","buyerperson","buyertel","budget","bidopentime","agency","projectscope","winnerperson","winnertel","bidendtime","district","signendtime","buyeraddr","buyerclass","s_topscopeclass","entidlist"`
  1184. }
  1185. sql = sql[:len(sql)-1] + `,"_source":[` + dataexport_field + "]}"
  1186. }
  1187. //分页排序
  1188. sql = sql[:len(sql)-1] + `,"sort": {"dataweight": "desc","publishtime":"desc","id":"desc"},"from":` + strconv.Itoa(start) + `,"size":` + strconv.Itoa(count) + "}"
  1189. }
  1190. log.Println("doSearch", sql)
  1191. return elastic.Get(INDEX, TYPE, sql)
  1192. }
  1193. func getKeyWordArrFromDbResult(k interface{}) (arr []KeyWord) {
  1194. if k == nil {
  1195. return
  1196. }
  1197. kArr := k.([]interface{})
  1198. for _, v := range kArr {
  1199. kw := KeyWord{}
  1200. b, e := json.Marshal(v)
  1201. if e != nil {
  1202. log.Println(e.Error())
  1203. }
  1204. json.Unmarshal(b, &kw)
  1205. arr = append(arr, kw)
  1206. }
  1207. return
  1208. }
  1209. func getStringArrFromDbResult(c interface{}) (arr []string) {
  1210. if c != nil {
  1211. cArr := c.([]interface{})
  1212. arr = qutil.ObjArrToStringArr(cArr)
  1213. }
  1214. return
  1215. }
  1216. // 获取结果,空字段最少的数据
  1217. func ScreenData(arr *[]map[string]interface{}, dataType string, resultNum int, kws []KeyWord) (res []map[string]interface{}) {
  1218. AllMap := map[int][]map[string]interface{}{}
  1219. NoKwsMap := map[int][]map[string]interface{}{}
  1220. lastNum := resultNum
  1221. for _, v := range *arr {
  1222. emptyNum := countOfTheEmpty(v, dataType)
  1223. if emptyNum == -1 {
  1224. continue
  1225. }
  1226. if len(kws) > 0 && kws[0].Keyword != "" {
  1227. var kwsFlag = true
  1228. for _, vk := range kws {
  1229. if strings.Contains(qutil.ObjToString(v["title"]), strings.Replace(vk.Keyword, "+", "", -1)) {
  1230. kwsFlag = false
  1231. continue
  1232. }
  1233. }
  1234. if kwsFlag {
  1235. if NoKwsMap[emptyNum] == nil {
  1236. NoKwsMap[emptyNum] = []map[string]interface{}{v}
  1237. } else {
  1238. NoKwsMap[emptyNum] = append(NoKwsMap[emptyNum], v)
  1239. }
  1240. continue
  1241. }
  1242. }
  1243. if AllMap[emptyNum] == nil {
  1244. AllMap[emptyNum] = []map[string]interface{}{v}
  1245. continue
  1246. }
  1247. AllMap[emptyNum] = append(AllMap[emptyNum], v)
  1248. }
  1249. //获取key
  1250. keys := []int{}
  1251. for k, _ := range AllMap {
  1252. keys = append(keys, k)
  1253. }
  1254. sort.Ints(keys)
  1255. //选取结果
  1256. for _, v := range keys {
  1257. if len(AllMap[v]) >= resultNum {
  1258. return append(res, AllMap[v][:resultNum]...)
  1259. } else {
  1260. resultNum = resultNum - len(AllMap[v])
  1261. tmp := append(res, AllMap[v][:len(AllMap[v])]...)
  1262. res = tmp
  1263. }
  1264. }
  1265. if len(res) < lastNum {
  1266. resultNum = lastNum - len(res)
  1267. //获取key
  1268. Nokeys := []int{}
  1269. for k, _ := range NoKwsMap {
  1270. Nokeys = append(Nokeys, k)
  1271. }
  1272. sort.Ints(Nokeys)
  1273. log.Println("没关键词的空字段数量", Nokeys)
  1274. //选取结果
  1275. for _, v := range Nokeys {
  1276. if len(NoKwsMap[v]) >= resultNum {
  1277. return append(res, NoKwsMap[v][:resultNum]...)
  1278. } else {
  1279. resultNum = resultNum - len(NoKwsMap[v])
  1280. tmp := append(res, NoKwsMap[v][:len(NoKwsMap[v])]...)
  1281. res = tmp
  1282. }
  1283. }
  1284. }
  1285. return res
  1286. }
  1287. func countOfTheEmpty(m map[string]interface{}, dataType string) int {
  1288. MsgType := m["subtype"]
  1289. // if MsgType == "拟建" {
  1290. // return -1
  1291. // }
  1292. //计算空字段数量
  1293. var count int = 0
  1294. //高级字段包
  1295. if dataType == "2" {
  1296. if m["href"] == "" || m["href"] == nil {
  1297. count++
  1298. }
  1299. if m["projectcode"] == "" || m["projectcode"] == nil {
  1300. count++
  1301. }
  1302. if m["buyerperson"] == "" || m["buyerperson"] == nil {
  1303. count++
  1304. }
  1305. if m["buyertel"] == "" || m["buyertel"] == nil {
  1306. count++
  1307. }
  1308. if m["budget"] == "" || m["budget"] == nil {
  1309. count++
  1310. }
  1311. if m["bidopentime"] == "" || m["bidopentime"] == nil {
  1312. count++
  1313. }
  1314. if m["agency"] == "" || m["agency"] == nil {
  1315. count++
  1316. }
  1317. if m["projectscope"] == "" || m["projectscope"] == nil {
  1318. count++
  1319. }
  1320. }
  1321. if m["city"] == "" || m["city"] == nil {
  1322. count++
  1323. }
  1324. if m["publishtime"] == "" || m["publishtime"] == nil {
  1325. count++
  1326. }
  1327. if m["projectname"] == "" || m["projectname"] == nil {
  1328. count++
  1329. }
  1330. if m["buyer"] == "" || m["buyer"] == nil {
  1331. count++
  1332. }
  1333. if m["s_winner"] == "" || m["s_winner"] == nil {
  1334. if MsgType != "招标" {
  1335. count++
  1336. }
  1337. }
  1338. if m["bidamount"] == "" || m["bidamount"] == nil {
  1339. if MsgType != "招标" {
  1340. count++
  1341. }
  1342. }
  1343. if m["subtype"] == "" || m["subtype"] == nil {
  1344. count++
  1345. }
  1346. return count
  1347. }