dataexport.go 57 KB

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