dataexport.go 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590
  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, "+", " "), " ")
  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, "+", " "), " ")
  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, "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,
  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. log.Println(scd.Id, "GetDataExportSelectResultFromMongoDb===", idArr[0])
  790. var (
  791. queryIds []interface{}
  792. count int
  793. )
  794. for _, idStr := range idArr {
  795. queryIds = append(queryIds, mg.StringTOBsonId(idStr))
  796. }
  797. iter := sess.DB(biddingName).C("bidding").Select(selectMap).Find(map[string]interface{}{"_id": map[string]interface{}{
  798. "$in": queryIds,
  799. }}).Iter()
  800. for m := make(map[string]interface{}); iter.Next(&m); {
  801. m["_id"] = mg.BsonIdToSId(m["_id"])
  802. detail, _ := m["detail"].(string)
  803. if detail != "" {
  804. m["detail"] = contentfilterReg.ReplaceAllString(detail, "")
  805. }
  806. count++
  807. returnLsit = append(returnLsit, m)
  808. m = make(map[string]interface{})
  809. }
  810. if count != len(idArr) {
  811. iter_back := sess.DB(biddingName).C("bidding_back").Select(selectMap).Find(map[string]interface{}{"_id": map[string]interface{}{
  812. "$in": queryIds,
  813. }}).Iter()
  814. for m := make(map[string]interface{}); iter_back.Next(&m); {
  815. m["_id"] = mg.BsonIdToSId(m["_id"])
  816. detail, _ := m["detail"].(string)
  817. if detail != "" {
  818. m["detail"] = contentfilterReg.ReplaceAllString(detail, "")
  819. }
  820. returnLsit = append(returnLsit, m)
  821. m = make(map[string]interface{})
  822. }
  823. }
  824. idArr = []string{}
  825. }
  826. }
  827. if len(returnLsit) == checkCount || checkCount == -1 || checkCount == -2 {
  828. return &returnLsit, nil
  829. } else {
  830. return nil, fmt.Errorf("GetDataExportSelectResultFromMongoDb 选择数据导出异常 数据量期望%d条,实际查询%d条", checkCount, len(returnLsit))
  831. }
  832. }
  833. func GetDataExportIds(elasticAddress string, scd *SieveCondition, checkCount int) ([]string, error) {
  834. defer qutil.Catch()
  835. if scd == nil {
  836. return nil, errors.New("GetDataExportIds-未获取到查询信息")
  837. }
  838. if scd.SelectIds != nil {
  839. return scd.SelectIds, nil
  840. }
  841. var qstr string
  842. if scd.SearchMode == SearchModeAccurate {
  843. //获取查询语句
  844. qstr = getDataExportSql(scd)
  845. log.Printf("GetDataExportIds-%s-sql:%s\n", scd.Id, qstr)
  846. }
  847. //超级搜索一致的检索(防止数据导出和超级搜索数据量不一致)
  848. // 依据用户选择的搜索模式和搜索范围进行匹配,即不限制只能匹配标题,且不限制最多展示100条、针对输入的单个关键词分词后需要都包含
  849. if scd.Comeinfrom == "supersearchPage" && (len(scd.Keyword) != 0 || len(scd.Industry) != 0 || IsOnTheWhitelist(scd.UserId, scd.MgoUserId)) && len(scd.SelectIds) == 0 && scd.SearchMode == SearchModeFuzzy {
  850. if len(scd.Keyword) != 0 {
  851. searchTextSize := 0
  852. // 关键词分词
  853. if len(scd.Keyword) > 0 {
  854. searchTextSize = len([]rune(scd.Keyword[0].Keyword))
  855. }
  856. if searchTextSize > 0 {
  857. if secondKWS := jy.HttpEs(scd.Keyword[0].Keyword, "ik_smart", elasticAddress); secondKWS != "" {
  858. scd.Keyword[0].Keyword = jy.KeywordsProcessing(strings.ReplaceAll(secondKWS, "+", " "), " ")
  859. }
  860. }
  861. // 附加词分词
  862. for i := 0; i < len(scd.Keyword[0].Appended); i++ {
  863. appendTextSize := 0
  864. if len(scd.Keyword[0].Appended[i]) > 0 {
  865. appendTextSize = len([]rune(scd.Keyword[0].Appended[i]))
  866. }
  867. if appendTextSize > 0 {
  868. if secondKWS := jy.HttpEs(scd.Keyword[0].Appended[i], "ik_smart", elasticAddress); secondKWS != "" {
  869. scd.Keyword[0].Appended[i] = jy.KeywordsProcessing(strings.ReplaceAll(secondKWS, "+", " "), " ")
  870. }
  871. }
  872. }
  873. }
  874. qstr = getDataExportSql(scd)
  875. log.Printf("GetDataExportIds-%s-分词查询-sql:%s\n", scd.Id, qstr)
  876. }
  877. res := doSearchByBatch(qstr, "1", checkCount, fmt.Sprintf("%s-%s", "GetDataExportSearchResult", scd.Id))
  878. //获取信息id
  879. idArr := make([]string, 0, 0)
  880. for _, v := range res {
  881. if id := qutil.ObjToString(v["_id"]); id != "" {
  882. idArr = append(idArr, id)
  883. }
  884. }
  885. if checkCount != len(idArr) {
  886. return nil, fmt.Errorf("GetDataExportIds-%s-数据总量校验异常,期望:%d,实际:%d", scd.Id, checkCount, len(res))
  887. }
  888. return idArr, nil
  889. }
  890. // GetDataExportSearchResult 获取数据导出内容
  891. // entmg 高级字段包查询企业电话邮箱等字段
  892. // checkCount -1 预览500条
  893. func GetDataExportSearchResult(bid mg.MongodbSim, bidMgoDBName, elasticAddress string, scd *SieveCondition, dataType string, checkCount int) (*[]map[string]interface{}, error) {
  894. defer qutil.Catch()
  895. tm := time.Now()
  896. if scd == nil {
  897. return nil, errors.New("GetDataExportSearchResult-未获取到查询信息")
  898. }
  899. if scd.SelectIds != nil {
  900. idSelectDates, idSelectErr := GetDataExportSelectResultFromMongoDb(bid, bidMgoDBName, scd, dataType, checkCount)
  901. if idSelectErr != nil {
  902. return nil, idSelectErr
  903. }
  904. log.Printf("id:%s,查询耗时:%s\n", scd.Id, time.Now().Sub(tm))
  905. GetDataExportMatchKey(scd, idSelectDates)
  906. log.Printf("id:%s key匹配耗时:%s\n", scd.Id, time.Now().Sub(tm))
  907. return idSelectDates, idSelectErr
  908. }
  909. selectType := scd.SelectType
  910. var qstr string
  911. var res []map[string]interface{}
  912. if scd.SearchMode == SearchModeAccurate { // 搜索模式为精确查找
  913. //获取查询语句
  914. qstr = getDataExportSql(scd)
  915. log.Printf("GetDataExportSearchResult-%s-sql:%s\n", scd.Id, qstr)
  916. //数据导出数据查询
  917. res = doSearchByBatch(qstr, dataType, checkCount, fmt.Sprintf("%s-%s", "GetDataExportSearchResult", scd.Id))
  918. }
  919. //超级搜索一致的检索(防止数据导出和超级搜索数据量不一致)
  920. if scd.Comeinfrom == "supersearchPage" && (len(scd.Keyword) != 0 || len(scd.Industry) != 0 || IsOnTheWhitelist(scd.UserId, scd.MgoUserId)) && len(scd.SelectIds) == 0 && scd.SearchMode == SearchModeFuzzy {
  921. if len(scd.Keyword) != 0 {
  922. searchTextSize := 0
  923. // 关键词分词
  924. if len(scd.Keyword) > 0 {
  925. searchTextSize = len([]rune(scd.Keyword[0].Keyword))
  926. }
  927. if searchTextSize > 0 {
  928. if secondKWS := jy.HttpEs(scd.Keyword[0].Keyword, "ik_smart", elasticAddress); secondKWS != "" {
  929. scd.Keyword[0].Keyword = jy.KeywordsProcessing(strings.ReplaceAll(secondKWS, "+", " "), " ")
  930. }
  931. }
  932. // 附加词分词
  933. for i := 0; i < len(scd.Keyword[0].Appended); i++ {
  934. appendTextSize := 0
  935. if len(scd.Keyword[0].Appended[i]) > 0 {
  936. appendTextSize = len([]rune(scd.Keyword[0].Appended[i]))
  937. }
  938. if appendTextSize > 0 {
  939. if secondKWS := jy.HttpEs(scd.Keyword[0].Appended[i], "ik_smart", elasticAddress); secondKWS != "" {
  940. scd.Keyword[0].Appended[i] = jy.KeywordsProcessing(strings.ReplaceAll(secondKWS, "+", " "), " ")
  941. }
  942. }
  943. }
  944. }
  945. qstr = getDataExportSql(scd)
  946. log.Printf("GetDataExportSearchResult-%s-分词查询-sql:%s\n", scd.Id, qstr)
  947. res = doSearchByBatch(qstr, dataType, checkCount, fmt.Sprintf("%s-%s", "GetDataExportSearchResult", scd.Id))
  948. }
  949. //校验数量
  950. if checkCount != len(res) && checkCount != -1 {
  951. return nil, fmt.Errorf("GetDataExportSearchResult-%s-数据总量校验异常,期望:%d,实际:%d", scd.Id, checkCount, len(res))
  952. }
  953. if selectType != scd.SelectType {
  954. scd.SelectType = selectType
  955. }
  956. log.Printf("id:%s 查询耗时:%s\n", scd.Id, time.Now().Sub(tm))
  957. GetDataExportMatchKey(scd, &res)
  958. log.Printf("id:%s key匹配耗时:%s\n", scd.Id, time.Now().Sub(tm))
  959. return &res, nil
  960. }
  961. // 数据导出内容标签
  962. func GetDataExportMatchKeyTag(mysqlSess *mysql.Mysql, res []map[string]interface{}, userId string, limit int) {
  963. userBidTagMap := make(map[string]string)
  964. 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))
  965. if userBidTag != nil && len(*userBidTag) > 0 {
  966. for _, s2 := range *userBidTag {
  967. userBidTagMap[qutil.InterfaceToStr(s2["bid"])] = qutil.InterfaceToStr(s2["labelname"])
  968. }
  969. }
  970. for _, re := range res {
  971. var tName string
  972. if tagName := userBidTagMap[qutil.InterfaceToStr(re["_id"])]; tagName != "" {
  973. tName = tagName
  974. } else {
  975. tName = "默认收藏"
  976. }
  977. re["tagName"] = tName
  978. }
  979. }
  980. func doSearchByBatch(query, dataType string, searchCount int, flag string) (res []map[string]interface{}) {
  981. if searchCount > onceSearchCount { //分批次查询
  982. batchNum := qutil.IntAll(math.Ceil(float64(searchCount) / float64(onceSearchCount)))
  983. var searchWaitGroup = &sync.WaitGroup{}
  984. var lock sync.Mutex
  985. for n := 0; n < batchNum; n++ {
  986. searchWaitGroup.Add(1)
  987. searchPool <- true
  988. go func(start int) {
  989. defer func() {
  990. searchWaitGroup.Done()
  991. <-searchPool
  992. }()
  993. checkNum, checkOk := onceSearchCount, false
  994. if start == (batchNum - 1) {
  995. if searchCount%onceSearchCount != 0 {
  996. checkNum = searchCount % onceSearchCount
  997. }
  998. }
  999. var tmp *[]map[string]interface{}
  1000. for i := 0; i < 3; i++ {
  1001. tmp = doSearch(query, start*onceSearchCount, onceSearchCount, dataType)
  1002. if tmp != nil && (len(*tmp) == checkNum) { //校验数据量是否够
  1003. checkOk = true
  1004. break
  1005. }
  1006. }
  1007. if tmp == nil {
  1008. log.Printf("%s-第%d页数据查询结果为空\n", flag, start+1)
  1009. return
  1010. }
  1011. if checkOk {
  1012. log.Printf("%s-第%d页数据加载完成,共%d条\n", flag, start+1, len(*tmp))
  1013. } else {
  1014. log.Printf("%s-第%d页数据加载异常,共%d条,预期%d条\n", flag, start+1, len(*tmp), checkNum)
  1015. }
  1016. lock.Lock()
  1017. res = append(res, *tmp...)
  1018. lock.Unlock()
  1019. }(n)
  1020. }
  1021. searchWaitGroup.Wait()
  1022. log.Printf("%s-分批次加载数据总量为%d\n", flag, len(res))
  1023. } else {
  1024. //queryCount := qutil.If(searchCount == -1, onceSearchCount, searchCount).(int)
  1025. queryCount := qutil.If(searchCount == -1, PreviewSearchCount, searchCount).(int)
  1026. searchPool <- true
  1027. tmp := doSearch(query, 0, queryCount, dataType)
  1028. <-searchPool
  1029. if tmp == nil || len(*tmp) == 0 {
  1030. log.Printf("%s-一次性加载数据异常\n", flag)
  1031. } else {
  1032. res = *tmp
  1033. log.Printf("%s-一次性加载数据总量为%d\n", flag, len(res))
  1034. }
  1035. }
  1036. return
  1037. }
  1038. func FormatExportData(entmg mg.MongodbSim, data *[]map[string]interface{}, webdomain string, dataType string, encry ...bool) *[]map[string]interface{} {
  1039. //格式化输出
  1040. isEncry := false
  1041. if len(encry) > 0 {
  1042. isEncry = true
  1043. }
  1044. if data == nil {
  1045. return data
  1046. }
  1047. sort.Slice(*data, func(i, j int) bool {
  1048. time1 := qutil.Int64All((*data)[i]["publishtime"])
  1049. time2 := qutil.Int64All((*data)[j]["publishtime"])
  1050. return time1 > time2
  1051. })
  1052. qyxyMap := make(map[string]bool)
  1053. qyxyEsMap := make(map[string]map[string]interface{})
  1054. projectsetMap := make(map[string]bool)
  1055. projectsetEsMap := make(map[string]map[string]interface{})
  1056. if dataType == "2" {
  1057. wait := &sync.WaitGroup{}
  1058. for _, m := range *data {
  1059. entidlist, ok := m["entidlist"].([]interface{})
  1060. if ok && len(entidlist) > 0 {
  1061. //var winnerMaps []map[string]interface{}
  1062. for _, entIdObj := range entidlist {
  1063. entId := qutil.ObjToString(entIdObj)
  1064. if entId == "" {
  1065. continue
  1066. }
  1067. qyxyMap[entId] = true
  1068. }
  1069. }
  1070. if m["toptype"] == "结果" && !(m["agency"] != nil && m["budget"] != nil && m["buyerperson"] != nil && m["buyertel"] != nil) {
  1071. projectsetMap[qutil.InterfaceToStr(m["_id"])] = true
  1072. }
  1073. }
  1074. log.Println(fmt.Sprintf("查询企业:%d,查询项目:%d", len(qyxyMap), len(projectsetMap)))
  1075. if len(qyxyMap) > 0 { //查询企业
  1076. wait.Add(1)
  1077. go func() {
  1078. var (
  1079. qyxyArr []string
  1080. qCount int
  1081. )
  1082. defer wait.Done()
  1083. pool := make(chan bool, 5)
  1084. qyxyWait := &sync.WaitGroup{}
  1085. lock := &sync.Mutex{}
  1086. for s := range qyxyMap {
  1087. qCount++
  1088. qyxyArr = append(qyxyArr, fmt.Sprintf(`%s`, s))
  1089. if len(qyxyArr) == 200 || (qCount == len(qyxyMap) && len(qyxyArr) > 0) {
  1090. pool <- true
  1091. qyxyWait.Add(1)
  1092. go func(qArr []string) {
  1093. defer func() {
  1094. <-pool
  1095. qyxyWait.Done()
  1096. }()
  1097. 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)))
  1098. if qyxyEsData != nil && len(*qyxyEsData) > 0 {
  1099. for _, m := range *qyxyEsData {
  1100. lock.Lock()
  1101. qyxyEsMap[qutil.InterfaceToStr(m["id"])] = m
  1102. lock.Unlock()
  1103. }
  1104. }
  1105. }(qyxyArr)
  1106. qyxyArr = []string{}
  1107. }
  1108. }
  1109. qyxyWait.Wait()
  1110. }()
  1111. }
  1112. if len(projectsetMap) > 0 { //查询项目
  1113. wait.Add(1)
  1114. go func() {
  1115. defer wait.Done()
  1116. var (
  1117. projectsetArr []string
  1118. pCount int
  1119. )
  1120. pool := make(chan bool, 5)
  1121. projectsetWait := &sync.WaitGroup{}
  1122. lock := &sync.Mutex{}
  1123. for s := range projectsetMap {
  1124. pCount++
  1125. projectsetArr = append(projectsetArr, fmt.Sprintf(`%s`, s))
  1126. if len(projectsetArr) == 200 || (pCount == len(projectsetMap) && len(projectsetArr) > 0) {
  1127. pool <- true
  1128. projectsetWait.Add(1)
  1129. go func(pArr []string) {
  1130. defer func() {
  1131. <-pool
  1132. projectsetWait.Done()
  1133. }()
  1134. projectsetEsData := elastic.Get("projectset", "projectset", fmt.Sprintf(`{"query": {"bool": {"should": [{"terms": {"list.infoid": ["%s"]}}]}},"_source": ["list"],"size": %d}`, strings.Join(pArr, `","`), len(pArr)*2)) //查询双倍数量 避免缺失数据
  1135. if projectsetEsData != nil && len(*projectsetEsData) > 0 {
  1136. for _, m := range *projectsetEsData {
  1137. MsgList := m["list"]
  1138. if MsgList != nil {
  1139. list := qutil.ObjArrToMapArr(MsgList.([]interface{}))
  1140. for _, m2 := range list {
  1141. if projectsetMap[qutil.InterfaceToStr(m2["infoid"])] {
  1142. lock.Lock()
  1143. projectsetEsMap[qutil.InterfaceToStr(m2["infoid"])] = m
  1144. lock.Unlock()
  1145. }
  1146. }
  1147. }
  1148. }
  1149. }
  1150. }(projectsetArr)
  1151. projectsetArr = []string{}
  1152. }
  1153. }
  1154. projectsetWait.Wait()
  1155. }()
  1156. }
  1157. wait.Wait()
  1158. }
  1159. var entCacheMap = map[string]map[string]interface{}{}
  1160. pool := make(chan bool, 5)
  1161. wait := &sync.WaitGroup{}
  1162. lock := &sync.Mutex{}
  1163. for index := 0; index < len(*data); index++ {
  1164. pool <- true
  1165. wait.Add(1)
  1166. go func(v map[string]interface{}) {
  1167. defer qutil.Catch()
  1168. defer func() {
  1169. <-pool
  1170. wait.Done()
  1171. }()
  1172. //有中标企业 且 高级字段查询
  1173. if dataType == "2" {
  1174. //查询企业公示 法人 公司电话 公司邮箱地址
  1175. entidlist, ok := v["entidlist"].([]interface{})
  1176. if ok && len(entidlist) > 0 {
  1177. var winnerMaps []map[string]interface{}
  1178. for _, entIdObj := range entidlist {
  1179. entId := qutil.ObjToString(entIdObj)
  1180. if entId == "" {
  1181. continue
  1182. }
  1183. lock.Lock()
  1184. ecm := entCacheMap[entId]
  1185. lock.Unlock()
  1186. if ecm != nil {
  1187. winnerMaps = append(winnerMaps, ecm)
  1188. //} 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 {
  1189. } else if entDetail := qyxyEsMap[entId]; entDetail != nil && len(entDetail) > 0 {
  1190. thisEntMap := map[string]interface{}{}
  1191. legal_person := ""
  1192. if (entDetail)["legal_person"] != nil {
  1193. legal_person = (entDetail)["legal_person"].(string)
  1194. if isEncry {
  1195. var xx = "*"
  1196. switch len([]rune(legal_person)) {
  1197. case 3:
  1198. xx = "**"
  1199. case 4:
  1200. xx = "***"
  1201. }
  1202. legal_person = string([]rune(legal_person)[:1]) + xx
  1203. }
  1204. }
  1205. company_phone := ""
  1206. if entDetail["company_phone"] != nil {
  1207. company_phone = entDetail["company_phone"].(string)
  1208. if isEncry {
  1209. if len([]rune(company_phone)) > 7 {
  1210. company_phone = company_phone[:7] + "****"
  1211. } else {
  1212. company_phone = "****"
  1213. }
  1214. }
  1215. }
  1216. company_email := ""
  1217. if entDetail["company_email"] != nil && entDetail["company_email"] != "无" {
  1218. company_email = entDetail["company_email"].(string)
  1219. if isEncry {
  1220. if len(strings.Split(company_email, "@")) > 1 {
  1221. company_email = "******" + "@" + strings.Split(company_email, "@")[1]
  1222. }
  1223. }
  1224. }
  1225. company_name := ""
  1226. if entDetail["company_name"] != nil {
  1227. company_name = entDetail["company_name"].(string)
  1228. }
  1229. thisEntMap["legal_person"] = legal_person
  1230. thisEntMap["company_phone"] = company_phone
  1231. thisEntMap["company_email"] = company_email
  1232. thisEntMap["company_name"] = company_name
  1233. lock.Lock()
  1234. entCacheMap[entId] = thisEntMap
  1235. lock.Unlock()
  1236. winnerMaps = append(winnerMaps, thisEntMap)
  1237. }
  1238. }
  1239. if len(winnerMaps) > 0 {
  1240. v["winnerMaps"] = winnerMaps
  1241. }
  1242. }
  1243. delete(v, "entidlist")
  1244. }
  1245. //====================字段补漏=========================
  1246. //if v["toptype"] == "结果" && dataType == "2" && !(v["agency"] != nil && v["budget"] != nil && v["buyerperson"] != nil && v["buyertel"] != nil) {
  1247. if r := projectsetEsMap[qutil.InterfaceToStr(v["_id"])]; r != nil && len(r) > 0 {
  1248. //r := elastic.Get("projectset", "projectset", fmt.Sprintf(`{"query":{"term":{"list.infoid":"%s"}},"_source": ["list"]}`, v["_id"]))
  1249. //if r != nil && len(*r) > 0 {
  1250. MsgList := r["list"]
  1251. if MsgList != nil {
  1252. list := qutil.ObjArrToMapArr(MsgList.([]interface{}))
  1253. for _, vv := range list {
  1254. if vv["subtype"] == "招标" {
  1255. if v["agency"] == nil && vv["agency"] != nil {
  1256. v["agency"] = vv["agency"]
  1257. }
  1258. if v["budget"] == nil && vv["budget"] != nil {
  1259. v["budget"] = vv["budget"]
  1260. }
  1261. if v["buyerperson"] == nil && vv["buyerperson"] != nil {
  1262. v["buyerperson"] = vv["buyerperson"]
  1263. }
  1264. if v["buyertel"] == nil && vv["buyertel"] != nil {
  1265. v["buyertel"] = vv["buyertel"]
  1266. }
  1267. break
  1268. }
  1269. }
  1270. }
  1271. //}
  1272. }
  1273. if v["area"] == "A" {
  1274. v["area"] = "全国"
  1275. }
  1276. if v["bidamount"] != nil {
  1277. v["bidamount"] = formatFloat(qutil.Float64All(v["bidamount"]))
  1278. }
  1279. if v["budget"] != nil {
  1280. v["budget"] = formatFloat(qutil.Float64All(v["budget"]))
  1281. }
  1282. if v["publishtime"] != nil {
  1283. date := v["publishtime"]
  1284. v["publishtime"] = FormatDateWithObj(&date, Date_Short_Layout)
  1285. }
  1286. if v["bidopentime"] != nil {
  1287. date := v["bidopentime"]
  1288. v["bidopentime"] = FormatDateWithObj(&date, Date_Short_Layout)
  1289. }
  1290. if qutil.IntAll(v["signendtime"]) != 0 {
  1291. date := v["signendtime"]
  1292. v["signendtime"] = FormatDateWithObj(&date, Date_Short_Layout)
  1293. }
  1294. if v["bidendtime"] != nil {
  1295. date := v["bidendtime"]
  1296. v["bidendtime"] = FormatDateWithObj(&date, Date_Short_Layout)
  1297. }
  1298. if v["signaturedate"] != nil {
  1299. date := v["signaturedate"]
  1300. v["signaturedate"] = FormatDateWithObj(&date, Date_Short_Layout)
  1301. }
  1302. if v["_id"] != nil {
  1303. encodeId := CommonEncodeArticle("content", v["_id"].(string))
  1304. v["url"] = webdomain + "/article/content/" + encodeId + ".html"
  1305. v["url_jump"] = webdomain + "/front/reloadTo/article/content/" + encodeId + ".html"
  1306. }
  1307. if v["currency"] == "" || v["currency"] == nil {
  1308. v["currency"] = "人民币"
  1309. }
  1310. if isEncry {
  1311. if v["projectscope"] != "" && v["projectscope"] != nil {
  1312. str := ClearHtml.ReplaceAllString(v["projectscope"].(string), "")
  1313. str = ClearOther.ReplaceAllString(str, "")
  1314. str = strings.Replace(str, " ", "", -1)
  1315. if len([]rune(str)) > 100 {
  1316. str = qutil.SubString(str, 0, 100) + "..."
  1317. }
  1318. v["projectscope"] = str
  1319. }
  1320. if v["detail"] != "" && v["detail"] != nil {
  1321. str := ClearHtml.ReplaceAllString(v["detail"].(string), "")
  1322. str = ClearOther.ReplaceAllString(str, "")
  1323. str = strings.Replace(str, " ", "", -1)
  1324. if len([]rune(str)) > 100 {
  1325. str = qutil.SubString(str, 0, 100) + "..."
  1326. }
  1327. v["detail"] = str
  1328. }
  1329. if v["title"] != "" && v["title"] != nil {
  1330. str := ClearHtml.ReplaceAllString(v["title"].(string), "")
  1331. str = ClearOther.ReplaceAllString(str, "")
  1332. str = strings.Replace(str, " ", "", -1)
  1333. if len([]rune(str)) > 100 {
  1334. str = qutil.SubString(str, 0, 100) + "..."
  1335. }
  1336. v["title"] = str
  1337. }
  1338. }
  1339. if v["subtype"] == nil && v["toptype"] != nil {
  1340. v["subtype"] = v["toptype"]
  1341. }
  1342. }((*data)[index])
  1343. }
  1344. wait.Wait()
  1345. return data
  1346. }
  1347. // 保留到0.01分
  1348. func formatFloat(value float64) string {
  1349. str := strings.TrimRight(fmt.Sprintf("%.7f", value*10000/100000000), "0")
  1350. if str[len(str)-1:] == "." {
  1351. return str[:len(str)-1]
  1352. }
  1353. return str
  1354. }
  1355. func doSearch(sql string, start, count int, dataType string) *[]map[string]interface{} {
  1356. if sql != "" {
  1357. //筛选字段
  1358. if dataType != "" {
  1359. dataexport_field := bidBaseField
  1360. if dataType == "2" {
  1361. dataexport_field = bidseniorField
  1362. }
  1363. sql = sql[:len(sql)-1] + `,"_source":[` + dataexport_field + "]}"
  1364. }
  1365. //分页排序
  1366. sql = sql[:len(sql)-1] + `,"sort": {"dataweight": "desc","publishtime":"desc","id":"desc"},"from":` + strconv.Itoa(start) + `,"size":` + strconv.Itoa(count) + "}"
  1367. }
  1368. log.Println("doSearch", sql)
  1369. return elastic.Get(INDEX, TYPE, sql)
  1370. }
  1371. func getKeyWordArrFromDbResult(k interface{}) (arr []KeyWord) {
  1372. if k == nil {
  1373. return
  1374. }
  1375. kArr := k.([]interface{})
  1376. for _, v := range kArr {
  1377. kw := KeyWord{}
  1378. b, e := json.Marshal(v)
  1379. if e != nil {
  1380. log.Println(e.Error())
  1381. }
  1382. json.Unmarshal(b, &kw)
  1383. arr = append(arr, kw)
  1384. }
  1385. return
  1386. }
  1387. func getStringArrFromDbResult(c interface{}) (arr []string) {
  1388. if c != nil {
  1389. cArr := c.([]interface{})
  1390. arr = qutil.ObjArrToStringArr(cArr)
  1391. }
  1392. return
  1393. }
  1394. // 获取结果,空字段最少的数据
  1395. func ScreenData(arr *[]map[string]interface{}, dataType string, resultNum int, kws []KeyWord) (res []map[string]interface{}) {
  1396. AllMap := map[int][]map[string]interface{}{}
  1397. NoKwsMap := map[int][]map[string]interface{}{}
  1398. lastNum := resultNum
  1399. for _, v := range *arr {
  1400. emptyNum := countOfTheEmpty(v, dataType)
  1401. if emptyNum == -1 {
  1402. continue
  1403. }
  1404. if len(kws) > 0 && kws[0].Keyword != "" {
  1405. var kwsFlag = true
  1406. for _, vk := range kws {
  1407. if strings.Contains(qutil.ObjToString(v["title"]), strings.Replace(vk.Keyword, "+", "", -1)) {
  1408. kwsFlag = false
  1409. continue
  1410. }
  1411. }
  1412. if kwsFlag {
  1413. if NoKwsMap[emptyNum] == nil {
  1414. NoKwsMap[emptyNum] = []map[string]interface{}{v}
  1415. } else {
  1416. NoKwsMap[emptyNum] = append(NoKwsMap[emptyNum], v)
  1417. }
  1418. continue
  1419. }
  1420. }
  1421. if AllMap[emptyNum] == nil {
  1422. AllMap[emptyNum] = []map[string]interface{}{v}
  1423. continue
  1424. }
  1425. AllMap[emptyNum] = append(AllMap[emptyNum], v)
  1426. }
  1427. //获取key
  1428. keys := []int{}
  1429. for k, _ := range AllMap {
  1430. keys = append(keys, k)
  1431. }
  1432. sort.Ints(keys)
  1433. //选取结果
  1434. for _, v := range keys {
  1435. if len(AllMap[v]) >= resultNum {
  1436. return append(res, AllMap[v][:resultNum]...)
  1437. } else {
  1438. resultNum = resultNum - len(AllMap[v])
  1439. tmp := append(res, AllMap[v][:len(AllMap[v])]...)
  1440. res = tmp
  1441. }
  1442. }
  1443. if len(res) < lastNum {
  1444. resultNum = lastNum - len(res)
  1445. //获取key
  1446. Nokeys := []int{}
  1447. for k, _ := range NoKwsMap {
  1448. Nokeys = append(Nokeys, k)
  1449. }
  1450. sort.Ints(Nokeys)
  1451. log.Println("没关键词的空字段数量", Nokeys)
  1452. //选取结果
  1453. for _, v := range Nokeys {
  1454. if len(NoKwsMap[v]) >= resultNum {
  1455. return append(res, NoKwsMap[v][:resultNum]...)
  1456. } else {
  1457. resultNum = resultNum - len(NoKwsMap[v])
  1458. tmp := append(res, NoKwsMap[v][:len(NoKwsMap[v])]...)
  1459. res = tmp
  1460. }
  1461. }
  1462. }
  1463. return res
  1464. }
  1465. func countOfTheEmpty(m map[string]interface{}, dataType string) int {
  1466. MsgType := m["subtype"]
  1467. // if MsgType == "拟建" {
  1468. // return -1
  1469. // }
  1470. //计算空字段数量
  1471. var count int = 0
  1472. //高级字段包
  1473. if dataType == "2" {
  1474. if m["href"] == "" || m["href"] == nil {
  1475. count++
  1476. }
  1477. if m["projectcode"] == "" || m["projectcode"] == nil {
  1478. count++
  1479. }
  1480. if m["buyerperson"] == "" || m["buyerperson"] == nil {
  1481. count++
  1482. }
  1483. if m["buyertel"] == "" || m["buyertel"] == nil {
  1484. count++
  1485. }
  1486. if m["budget"] == "" || m["budget"] == nil {
  1487. count++
  1488. }
  1489. if m["bidopentime"] == "" || m["bidopentime"] == nil {
  1490. count++
  1491. }
  1492. if m["agency"] == "" || m["agency"] == nil {
  1493. count++
  1494. }
  1495. if m["projectscope"] == "" || m["projectscope"] == nil {
  1496. count++
  1497. }
  1498. }
  1499. if m["city"] == "" || m["city"] == nil {
  1500. count++
  1501. }
  1502. if m["publishtime"] == "" || m["publishtime"] == nil {
  1503. count++
  1504. }
  1505. if m["projectname"] == "" || m["projectname"] == nil {
  1506. count++
  1507. }
  1508. if m["buyer"] == "" || m["buyer"] == nil {
  1509. count++
  1510. }
  1511. if m["s_winner"] == "" || m["s_winner"] == nil {
  1512. if MsgType != "招标" {
  1513. count++
  1514. }
  1515. }
  1516. if m["bidamount"] == "" || m["bidamount"] == nil {
  1517. if MsgType != "招标" {
  1518. count++
  1519. }
  1520. }
  1521. if m["subtype"] == "" || m["subtype"] == nil {
  1522. count++
  1523. }
  1524. return count
  1525. }