main.go 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205
  1. package main
  2. /**
  3. 招标信息判重
  4. **/
  5. import (
  6. "encoding/json"
  7. "flag"
  8. "fmt"
  9. "github.com/cron"
  10. "log"
  11. mu "mfw/util"
  12. "net"
  13. "os"
  14. "qfw/util"
  15. "regexp"
  16. "sync"
  17. "time"
  18. "gopkg.in/mgo.v2/bson"
  19. )
  20. var (
  21. Sysconfig map[string]interface{} //配置文件
  22. mconf map[string]interface{} //mongodb配置信息
  23. mgo *MongodbSim //mongodb操作对象
  24. extract string
  25. extract_back string
  26. udpclient mu.UdpClient //udp对象
  27. nextNode []map[string]interface{} //下节点数组
  28. dupdays = 5 //初始化判重范围
  29. DM *datamap //
  30. HM *historymap //判重数据
  31. lastid = ""
  32. //正则筛选相关
  33. FilterRegTitle = regexp.MustCompile("^_$")
  34. FilterRegTitle_0 = regexp.MustCompile("^_$")
  35. FilterRegTitle_1 = regexp.MustCompile("^_$")
  36. FilterRegTitle_2 = regexp.MustCompile("^_$")
  37. isMerger bool //是否合并
  38. Is_Sort bool //是否排序
  39. threadNum int //线程数量
  40. SiteMap map[string]map[string]interface{} //站点map
  41. LowHeavy bool //低质量数据判重
  42. TimingTask bool //是否定时任务
  43. timingSpanDay int64 //时间跨度
  44. timingPubScope int64 //发布时间周期
  45. sid, eid string //测试人员判重使用
  46. )
  47. func init() {
  48. //5ea9a4800000000000000000
  49. flag.StringVar(&lastid, "id", "", "最后加载id") //以小于等于此id开始加载最近几天的数据
  50. flag.StringVar(&sid, "sid", "", "开始id")
  51. flag.StringVar(&eid, "eid", "", "结束id")
  52. flag.Parse()
  53. //172.17.145.163:27080
  54. util.ReadConfig(&Sysconfig)
  55. nextNode = util.ObjArrToMapArr(Sysconfig["nextNode"].([]interface{}))
  56. mconf = Sysconfig["mongodb"].(map[string]interface{})
  57. mgo = &MongodbSim{
  58. MongodbAddr: mconf["addr"].(string),
  59. DbName: mconf["db"].(string),
  60. Size: util.IntAllDef(mconf["pool"], 10),
  61. }
  62. mgo.InitPool()
  63. extract = mconf["extract"].(string)
  64. extract_back = mconf["extract_back"].(string)
  65. dupdays = util.IntAllDef(Sysconfig["dupdays"], 3)
  66. //加载数据
  67. DM = NewDatamap(dupdays, lastid)
  68. FilterRegTitle = regexp.MustCompile(util.ObjToString(Sysconfig["specialwords"]))
  69. FilterRegTitle_0 = regexp.MustCompile(util.ObjToString(Sysconfig["specialtitle_0"]))
  70. FilterRegTitle_1 = regexp.MustCompile(util.ObjToString(Sysconfig["specialtitle_1"]))
  71. FilterRegTitle_2 = regexp.MustCompile(util.ObjToString(Sysconfig["specialtitle_2"]))
  72. isMerger = Sysconfig["isMerger"].(bool)
  73. Is_Sort = Sysconfig["isSort"].(bool)
  74. threadNum = util.IntAllDef(Sysconfig["threads"], 1)
  75. LowHeavy = Sysconfig["lowHeavy"].(bool)
  76. TimingTask = Sysconfig["timingTask"].(bool)
  77. timingSpanDay = util.Int64All(Sysconfig["timingSpanDay"])
  78. timingPubScope = util.Int64All(Sysconfig["timingPubScope"])
  79. //站点配置
  80. site := mconf["site"].(map[string]interface{})
  81. SiteMap = make(map[string]map[string]interface{}, 0)
  82. start := int(time.Now().Unix())
  83. sess_site := mgo.GetMgoConn()
  84. defer mgo.DestoryMongoConn(sess_site)
  85. res_site := sess_site.DB(site["dbname"].(string)).C(site["coll"].(string)).Find(map[string]interface{}{}).Sort("_id").Iter()
  86. for site_dict := make(map[string]interface{}); res_site.Next(&site_dict); {
  87. data_map := map[string]interface{}{
  88. "area": util.ObjToString(site_dict["area"]),
  89. "city": util.ObjToString(site_dict["city"]),
  90. "district": util.ObjToString(site_dict["district"]),
  91. "sitetype": util.ObjToString(site_dict["sitetype"]),
  92. "level": util.ObjToString(site_dict["level"]),
  93. }
  94. SiteMap[util.ObjToString(site_dict["site"])] = data_map
  95. }
  96. log.Printf("new站点加载用时:%d秒,%d个\n", int(time.Now().Unix())-start, len(SiteMap))
  97. }
  98. func main() {
  99. //TestXiuFu()
  100. //return
  101. go checkMapJob()
  102. updport := Sysconfig["udpport"].(string)
  103. udpclient = mu.UdpClient{Local: updport, BufSize: 1024}
  104. udpclient.Listen(processUdpMsg)
  105. log.Println("Udp服务监听", updport)
  106. if TimingTask {
  107. go timedTaskDay()
  108. }
  109. time.Sleep(99999 * time.Hour)
  110. }
  111. //测试组人员使用
  112. func mainT() {
  113. /*
  114. ObjectId("5da3f31aa5cb26b9b798d3aa")
  115. ObjectId("5da418c4a5cb26b9b7e3e9a6")
  116. ObjectId("5da3f2c5a5cb26b9b79847fc")
  117. ObjectId("5db2735ba5cb26b9b7c99c6f")
  118. */
  119. if TimingTask {
  120. log.Println("定时任务测试开始")
  121. go timedTaskDay()
  122. time.Sleep(99999 * time.Hour)
  123. } else {
  124. //2020-4-24
  125. sid = "5ea1bb800000000000000000"
  126. eid = "5ea9a4800000000000000000"
  127. log.Println("正常判重测试开始")
  128. log.Println(sid, "---", eid)
  129. mapinfo := map[string]interface{}{}
  130. if sid == "" || eid == "" {
  131. log.Println("sid,eid参数不能为空")
  132. os.Exit(0)
  133. }
  134. mapinfo["gtid"] = sid
  135. mapinfo["lteid"] = eid
  136. mapinfo["stop"] = "true"
  137. task([]byte{}, mapinfo)
  138. time.Sleep(10 * time.Second)
  139. }
  140. }
  141. func processUdpMsg(act byte, data []byte, ra *net.UDPAddr) {
  142. fmt.Println("接受的段数据")
  143. switch act {
  144. case mu.OP_TYPE_DATA: //上个节点的数据
  145. //从表中开始处理
  146. var mapInfo map[string]interface{}
  147. err := json.Unmarshal(data, &mapInfo)
  148. log.Println("err:", err, "mapInfo:", mapInfo)
  149. if err != nil {
  150. udpclient.WriteUdp([]byte("err:"+err.Error()), mu.OP_NOOP, ra)
  151. } else if mapInfo != nil {
  152. taskType := util.ObjToString(mapInfo["stype"])
  153. if taskType == "historyTask" {
  154. //历史更新流程
  155. go historyTask(data, mapInfo)
  156. } else if taskType == "normalTask" {
  157. //判重流程
  158. go task(data, mapInfo)
  159. } else {
  160. //其他
  161. go task(data, mapInfo)
  162. }
  163. key, _ := mapInfo["key"].(string)
  164. if key == "" {
  165. key = "udpok"
  166. }
  167. udpclient.WriteUdp([]byte(key), mu.OP_NOOP, ra)
  168. }
  169. case mu.OP_NOOP: //下个节点回应
  170. ok := string(data)
  171. if ok != "" {
  172. log.Println("ok:", ok)
  173. udptaskmap.Delete(ok)
  174. }
  175. }
  176. }
  177. //开始判重程序
  178. func task(data []byte, mapInfo map[string]interface{}) {
  179. log.Println("开始数据判重")
  180. defer util.Catch()
  181. //区间id
  182. q := map[string]interface{}{
  183. "_id": map[string]interface{}{
  184. "$gt": StringTOBsonId(mapInfo["gtid"].(string)),
  185. "$lte": StringTOBsonId(mapInfo["lteid"].(string)),
  186. },
  187. }
  188. log.Println(mgo.DbName, extract, q)
  189. sess := mgo.GetMgoConn()
  190. defer mgo.DestoryMongoConn(sess)
  191. //是否排序
  192. it := sess.DB(mgo.DbName).C(extract).Find(&q).Sort("_id").Iter()
  193. if Is_Sort {
  194. log.Println("排序:publishtime")
  195. it = sess.DB(mgo.DbName).C(extract).Find(&q).Sort("publishtime").Iter()
  196. }
  197. //it = sess.DB(mgo.DbName).C(extract).Find(&q).Iter()
  198. updateExtract := [][]map[string]interface{}{}
  199. log.Println("线程数:", threadNum)
  200. pool := make(chan bool, threadNum)
  201. wg := &sync.WaitGroup{}
  202. n, repeateN := 0, 0
  203. for tmp := make(map[string]interface{}); it.Next(&tmp); n++ {
  204. if n%10000 == 0 {
  205. log.Println("current:", n, tmp["_id"], "repeateN:", repeateN)
  206. }
  207. if util.IntAll(tmp["repeat"]) == 1 || util.IntAll(tmp["repeat"]) == -1 {
  208. tmp = make(map[string]interface{})
  209. repeateN++
  210. continue
  211. }
  212. pool <- true
  213. wg.Add(1)
  214. go func(tmp map[string]interface{}) {
  215. defer func() {
  216. <-pool
  217. wg.Done()
  218. }()
  219. info := NewInfo(tmp)
  220. if !LowHeavy { //是否进行低质量数据判重
  221. if invalidData(info.buyer, info.projectname, info.projectcode, info.contractnumber) {
  222. updateExtract = append(updateExtract, []map[string]interface{}{
  223. map[string]interface{}{
  224. "_id": tmp["_id"],
  225. },
  226. map[string]interface{}{
  227. "$set": map[string]interface{}{
  228. "repeat": -1, //无效数据标签
  229. },
  230. },
  231. })
  232. if len(updateExtract) > 500 {
  233. mgo.UpSertBulk(extract, updateExtract...)
  234. updateExtract = [][]map[string]interface{}{}
  235. }
  236. return
  237. }
  238. }
  239. b, source, reason := DM.check(info)
  240. if b { //有重复,生成更新语句,更新抽取和更新招标
  241. repeateN++
  242. var is_replace = false
  243. var mergeArr = []int64{} //更改合并数组记录
  244. var newData = &Info{} //更换新的数据池数据
  245. var repeat_idMap = map[string]interface{}{} //记录判重的
  246. var merge_idMap = map[string]interface{}{} //记录合并的
  247. repeat_idMap["_id"] = StringTOBsonId(info.id)
  248. merge_idMap["_id"] = StringTOBsonId(source.id)
  249. repeat_id := source.id //初始化一个数据
  250. if isMerger { //合并相关
  251. basic_bool := basicDataScore(source, info)
  252. if basic_bool {
  253. //已原始数据为标准 - 对比数据打判重标签-
  254. newData, mergeArr, is_replace = mergeDataFields(source, info)
  255. DM.replaceSourceData(newData, source.id) //替换
  256. //对比数据打重复标签的id,原始数据id的记录
  257. repeat_idMap["_id"] = StringTOBsonId(info.id)
  258. merge_idMap["_id"] = StringTOBsonId(source.id)
  259. repeat_id = source.id
  260. } else {
  261. //已对比数据为标准 ,数据池的数据打判重标签
  262. newData, mergeArr, is_replace = mergeDataFields(info, source)
  263. DM.replaceSourceData(newData, source.id) //替换
  264. //原始数据打重复标签的id, 对比数据id的记录
  265. repeat_idMap["_id"] = StringTOBsonId(source.id)
  266. merge_idMap["_id"] = StringTOBsonId(info.id)
  267. repeat_id = info.id
  268. }
  269. merge_map := make(map[string]interface{}, 0)
  270. if is_replace { //有过合并-更新数据
  271. merge_map = map[string]interface{}{
  272. "$set": map[string]interface{}{
  273. "merge": newData.mergemap,
  274. },
  275. }
  276. //更新合并后的数据
  277. for _, value := range mergeArr {
  278. if value == 0 {
  279. merge_map["$set"].(map[string]interface{})["area"] = newData.area
  280. merge_map["$set"].(map[string]interface{})["city"] = newData.city
  281. } else if value == 1 {
  282. merge_map["$set"].(map[string]interface{})["area"] = newData.area
  283. merge_map["$set"].(map[string]interface{})["city"] = newData.city
  284. } else if value == 2 {
  285. merge_map["$set"].(map[string]interface{})["projectname"] = newData.projectname
  286. } else if value == 3 {
  287. merge_map["$set"].(map[string]interface{})["projectcode"] = newData.projectcode
  288. } else if value == 4 {
  289. merge_map["$set"].(map[string]interface{})["buyer"] = newData.buyer
  290. } else if value == 5 {
  291. merge_map["$set"].(map[string]interface{})["budget"] = newData.budget
  292. } else if value == 6 {
  293. merge_map["$set"].(map[string]interface{})["winner"] = newData.winner
  294. } else if value == 7 {
  295. merge_map["$set"].(map[string]interface{})["bidamount"] = newData.bidamount
  296. } else if value == 8 {
  297. merge_map["$set"].(map[string]interface{})["bidopentime"] = newData.bidopentime
  298. } else if value == 9 {
  299. merge_map["$set"].(map[string]interface{})["contractnumber"] = newData.contractnumber
  300. } else if value == 10 {
  301. merge_map["$set"].(map[string]interface{})["publishtime"] = newData.publishtime
  302. } else if value == 11 {
  303. merge_map["$set"].(map[string]interface{})["agency"] = newData.agency
  304. } else {
  305. }
  306. }
  307. //模板数据更新
  308. updateExtract = append(updateExtract, []map[string]interface{}{
  309. merge_idMap,
  310. merge_map,
  311. })
  312. }
  313. } else { //高质量数据
  314. basic_bool := basicDataScore(source, info)
  315. if !basic_bool {
  316. DM.replaceSourceData(info, source.id) //替换
  317. repeat_idMap["_id"] = StringTOBsonId(source.id)
  318. repeat_id = info.id
  319. }
  320. }
  321. log.Println("最终结果","目标id:",info.id)
  322. //重复数据打标签
  323. updateExtract = append(updateExtract, []map[string]interface{}{
  324. repeat_idMap,
  325. map[string]interface{}{
  326. "$set": map[string]interface{}{
  327. "repeat": 1,
  328. "repeat_reason": reason,
  329. "repeat_id": repeat_id,
  330. },
  331. },
  332. })
  333. }
  334. }(tmp)
  335. if len(updateExtract) > 500 {
  336. mgo.UpSertBulk(extract, updateExtract...)
  337. updateExtract = [][]map[string]interface{}{}
  338. }
  339. tmp = make(map[string]interface{})
  340. }
  341. wg.Wait()
  342. if len(updateExtract) > 0 {
  343. mgo.UpSertBulk(extract, updateExtract...)
  344. }
  345. log.Println("this task over.", n, "repeateN:", repeateN, mapInfo["stop"])
  346. //任务完成,开始发送广播通知下面节点
  347. if n > repeateN && mapInfo["stop"] == nil {
  348. for _, to := range nextNode {
  349. sid, _ := mapInfo["gtid"].(string)
  350. eid, _ := mapInfo["lteid"].(string)
  351. key := sid + "-" + eid + "-" + util.ObjToString(to["stype"])
  352. by, _ := json.Marshal(map[string]interface{}{
  353. "gtid": sid,
  354. "lteid": eid,
  355. "stype": util.ObjToString(to["stype"]),
  356. "key": key,
  357. })
  358. addr := &net.UDPAddr{
  359. IP: net.ParseIP(to["addr"].(string)),
  360. Port: util.IntAll(to["port"]),
  361. }
  362. node := &udpNode{by, addr, time.Now().Unix(), 0}
  363. udptaskmap.Store(key, node)
  364. udpclient.WriteUdp(by, mu.OP_TYPE_DATA, addr)
  365. }
  366. }
  367. }
  368. //支持历史更新
  369. func historyTask(data []byte, mapInfo map[string]interface{}) {
  370. fmt.Println("开始取历史时间段")
  371. defer util.Catch()
  372. sess := mgo.GetMgoConn()
  373. defer mgo.DestoryMongoConn(sess)
  374. q := map[string]interface{}{
  375. "_id": map[string]interface{}{
  376. "$gt": StringTOBsonId(mapInfo["gtid"].(string)),
  377. "$lte": StringTOBsonId(mapInfo["lteid"].(string)),
  378. },
  379. }
  380. it := sess.DB(mgo.DbName).C(extract).Find(&q).Iter()
  381. minTime, maxTime := int64(0), int64(0)
  382. for tmp := make(map[string]interface{}); it.Next(&tmp); {
  383. //取出最大最小时间
  384. info_time := tmp["comeintime"]
  385. if Is_Sort {
  386. info_time = tmp["publishtime"]
  387. }
  388. if minTime == 0 || maxTime == 0 && util.Int64All(info_time) != 0 {
  389. minTime = util.Int64All(info_time)
  390. maxTime = util.Int64All(info_time)
  391. } else {
  392. t := util.Int64All(info_time)
  393. if t < minTime && t != 0 {
  394. minTime = t
  395. }
  396. if t > maxTime && t != 0 {
  397. maxTime = t
  398. }
  399. }
  400. }
  401. //时间不正确时
  402. if minTime == 0 && maxTime == 0 {
  403. log.Println("段数据区间 不符合")
  404. return
  405. }
  406. fmt.Println("最小时间==", minTime, "最大时间==", maxTime)
  407. gtid, lteid := util.BsonIdToSId(mapInfo["gtid"].(string)), util.BsonIdToSId(mapInfo["lteid"].(string))
  408. fmt.Println(gtid, lteid)
  409. HM = NewHistorymap(gtid, lteid, minTime, maxTime)
  410. fmt.Println("开始历史数据判重")
  411. defer util.Catch()
  412. //区间id
  413. sess_history := mgo.GetMgoConn()
  414. defer mgo.DestoryMongoConn(sess_history)
  415. q_history := map[string]interface{}{
  416. "_id": map[string]interface{}{
  417. "$gt": StringTOBsonId(mapInfo["gtid"].(string)),
  418. "$lte": StringTOBsonId(mapInfo["lteid"].(string)),
  419. },
  420. }
  421. log.Println(mgo.DbName, extract, q_history)
  422. //是否排序
  423. it_history := sess_history.DB(mgo.DbName).C(extract).Find(&q_history).Iter()
  424. if Is_Sort {
  425. it_history = sess_history.DB(mgo.DbName).C(extract).Find(&q_history).Sort("publishtime").Iter()
  426. }
  427. updateExtract := [][]map[string]interface{}{}
  428. log.Println("线程数:", threadNum)
  429. pool := make(chan bool, threadNum)
  430. wg := &sync.WaitGroup{}
  431. n, repeateN := 0, 0
  432. for tmp := make(map[string]interface{}); it_history.Next(&tmp); n++ {
  433. if n%10000 == 0 {
  434. log.Println("current:", n, tmp["_id"], "repeateN:", repeateN)
  435. }
  436. if util.IntAll(tmp["dataging"]) == 1 {
  437. tmp = make(map[string]interface{})
  438. continue
  439. }
  440. pool <- true
  441. wg.Add(1)
  442. go func(tmp map[string]interface{}) {
  443. defer func() {
  444. <-pool
  445. wg.Done()
  446. }()
  447. info := NewInfo(tmp)
  448. if !LowHeavy { //是否进行低质量数据判重
  449. if invalidData(info.buyer, info.projectname, info.projectcode, info.contractnumber) {
  450. updateExtract = append(updateExtract, []map[string]interface{}{
  451. map[string]interface{}{
  452. "_id": tmp["_id"],
  453. },
  454. map[string]interface{}{
  455. "$set": map[string]interface{}{
  456. "repeat": -1, //无效数据标签
  457. },
  458. },
  459. })
  460. if len(updateExtract) > 500 {
  461. mgo.UpSertBulk(extract, updateExtract...)
  462. updateExtract = [][]map[string]interface{}{}
  463. }
  464. return
  465. }
  466. }
  467. b, source, reason := HM.checkHistory(info)
  468. if b { //有重复,生成更新语句,更新抽取和更新招标
  469. if reason == "未判重记录" {
  470. fmt.Println("未判重记录")
  471. //把info的数据判重的标签更换,并新增字段
  472. HM.replaceSourceData(info, info.id) //替换即添加
  473. updateExtract = append(updateExtract, []map[string]interface{}{
  474. map[string]interface{}{
  475. "_id": tmp["_id"],
  476. },
  477. map[string]interface{}{
  478. "$set": map[string]interface{}{
  479. "repeat": 0,
  480. "repeatid": -2,
  481. },
  482. },
  483. })
  484. } else {
  485. repeateN++
  486. var is_replace = false
  487. var mergeArr = []int64{} //更改合并数组记录
  488. var newData = &Info{} //更换新的数据池数据
  489. var repeat_idMap = map[string]interface{}{} //记录判重的
  490. var merge_idMap = map[string]interface{}{} //记录合并的
  491. repeat_idMap["_id"] = StringTOBsonId(info.id)
  492. merge_idMap["_id"] = StringTOBsonId(source.id)
  493. repeat_id := source.id
  494. //以下合并相关
  495. if isMerger {
  496. basic_bool := basicDataScore(source, info)
  497. if basic_bool {
  498. //已原始数据为标准 - 对比数据打判重标签-
  499. newData, mergeArr, is_replace = mergeDataFields(source, info)
  500. HM.replaceSourceData(newData, source.id) //替换
  501. //对比数据打重复标签的id,原始数据id的记录
  502. repeat_idMap["_id"] = StringTOBsonId(info.id)
  503. merge_idMap["_id"] = StringTOBsonId(source.id)
  504. repeat_id = source.id
  505. } else {
  506. //已对比数据为标准 ,数据池的数据打判重标签
  507. newData, mergeArr, is_replace = mergeDataFields(info, source)
  508. HM.replaceSourceData(newData, source.id) //替换
  509. //原始数据打重复标签的id, 对比数据id的记录
  510. repeat_idMap["_id"] = StringTOBsonId(source.id)
  511. merge_idMap["_id"] = StringTOBsonId(info.id)
  512. repeat_id = info.id
  513. }
  514. merge_map := make(map[string]interface{}, 0)
  515. if is_replace { //有过合并-更新数据
  516. merge_map = map[string]interface{}{
  517. "$set": map[string]interface{}{
  518. "merge": newData.mergemap,
  519. },
  520. }
  521. //更新合并后的数据
  522. for _, value := range mergeArr {
  523. if value == 0 {
  524. merge_map["$set"].(map[string]interface{})["area"] = newData.area
  525. merge_map["$set"].(map[string]interface{})["city"] = newData.city
  526. } else if value == 1 {
  527. merge_map["$set"].(map[string]interface{})["area"] = newData.area
  528. merge_map["$set"].(map[string]interface{})["city"] = newData.city
  529. } else if value == 2 {
  530. merge_map["$set"].(map[string]interface{})["projectname"] = newData.projectname
  531. } else if value == 3 {
  532. merge_map["$set"].(map[string]interface{})["projectcode"] = newData.projectcode
  533. } else if value == 4 {
  534. merge_map["$set"].(map[string]interface{})["buyer"] = newData.buyer
  535. } else if value == 5 {
  536. merge_map["$set"].(map[string]interface{})["budget"] = newData.budget
  537. } else if value == 6 {
  538. merge_map["$set"].(map[string]interface{})["winner"] = newData.winner
  539. } else if value == 7 {
  540. merge_map["$set"].(map[string]interface{})["bidamount"] = newData.bidamount
  541. } else if value == 8 {
  542. merge_map["$set"].(map[string]interface{})["bidopentime"] = newData.bidopentime
  543. } else if value == 9 {
  544. merge_map["$set"].(map[string]interface{})["contractnumber"] = newData.contractnumber
  545. } else if value == 10 {
  546. merge_map["$set"].(map[string]interface{})["publishtime"] = newData.publishtime
  547. } else if value == 11 {
  548. merge_map["$set"].(map[string]interface{})["agency"] = newData.agency
  549. } else {
  550. }
  551. }
  552. //模板数据更新
  553. updateExtract = append(updateExtract, []map[string]interface{}{
  554. merge_idMap,
  555. merge_map,
  556. })
  557. }
  558. } else { //高质量数据
  559. basic_bool := basicDataScore(source, info)
  560. if !basic_bool {
  561. HM.replaceSourceData(info, source.id) //替换
  562. repeat_idMap["_id"] = StringTOBsonId(source.id)
  563. repeat_id = info.id
  564. }
  565. }
  566. //重复数据打标签
  567. updateExtract = append(updateExtract, []map[string]interface{}{
  568. repeat_idMap,
  569. map[string]interface{}{
  570. "$set": map[string]interface{}{
  571. "repeat": 1,
  572. "repeat_reason": reason,
  573. "repeat_id": repeat_id,
  574. },
  575. },
  576. })
  577. }
  578. }
  579. }(tmp)
  580. if len(updateExtract) > 500 {
  581. mgo.UpSertBulk(extract, updateExtract...)
  582. updateExtract = [][]map[string]interface{}{}
  583. }
  584. tmp = make(map[string]interface{})
  585. }
  586. wg.Wait()
  587. if len(updateExtract) > 0 {
  588. mgo.UpSertBulk(extract, updateExtract...)
  589. //mgo.UpdateBulk(bidding, updateBidding...)
  590. }
  591. log.Println("this task over.", n, "repeateN:", repeateN, mapInfo["stop"])
  592. //任务完成,开始发送广播通知下面节点
  593. if n > repeateN && mapInfo["stop"] == nil {
  594. for _, to := range nextNode {
  595. sid, _ := mapInfo["gtid"].(string)
  596. eid, _ := mapInfo["lteid"].(string)
  597. key := sid + "-" + eid + "-" + util.ObjToString(to["stype"])
  598. by, _ := json.Marshal(map[string]interface{}{
  599. "gtid": sid,
  600. "lteid": eid,
  601. "stype": util.ObjToString(to["stype"]),
  602. "key": key,
  603. })
  604. addr := &net.UDPAddr{
  605. IP: net.ParseIP(to["addr"].(string)),
  606. Port: util.IntAll(to["port"]),
  607. }
  608. node := &udpNode{by, addr, time.Now().Unix(), 0}
  609. udptaskmap.Store(key, node)
  610. udpclient.WriteUdp(by, mu.OP_TYPE_DATA, addr)
  611. }
  612. }
  613. }
  614. //定时任务
  615. func timedTaskDay() {
  616. log.Println("部署定时任务")
  617. c := cron.New()
  618. c.AddFunc("0 0 1 * * ?", func() { movedata() }) //每天凌晨1点执行一次
  619. c.AddFunc("0 0 2 * * ?", func() { timedTaskOnce() }) //每天凌晨2点执行一次
  620. c.Start()
  621. //timedTaskOnce()
  622. }
  623. func timedTaskOnce() {
  624. log.Println("开始一次定时任务")
  625. defer util.Catch()
  626. now := time.Now()
  627. preTime := time.Date(now.Year(), now.Month(), now.Day()-1, 0, 0, 0, 0, time.Local)
  628. curTime := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local)
  629. task_sid := util.BsonIdToSId(bson.NewObjectIdWithTime(preTime))
  630. task_eid := util.BsonIdToSId(bson.NewObjectIdWithTime(curTime))
  631. between_time := curTime.Unix() - (86400 * timingPubScope)
  632. //task_sid = "5e9f18800000000000000000"
  633. //task_eid = "5ea06a000000000000000000"
  634. //between_time = int64(1525363200)
  635. log.Println("id区间:",task_sid, task_eid,"时间:", between_time)
  636. //区间id
  637. q_start := map[string]interface{}{
  638. "_id": map[string]interface{}{
  639. "$gte": StringTOBsonId(task_sid),
  640. "$lte": StringTOBsonId(task_eid),
  641. },
  642. }
  643. sess := mgo.GetMgoConn()
  644. defer mgo.DestoryMongoConn(sess)
  645. it_start := sess.DB(mgo.DbName).C(extract).Find(&q_start).Sort("publishtime").Iter()
  646. num,oknum, deterTime:= int64(0),int64(0),int64(0) //计数
  647. updateExtract := [][]map[string]interface{}{}//批量更新mongo数组
  648. pendAllArr:=[][]map[string]interface{}{}//待处理数组
  649. dayArr := []map[string]interface{}{}
  650. for tmp := make(map[string]interface{}); it_start.Next(&tmp); num++ {
  651. if num%10000 == 0 {
  652. log.Println("正序遍历:", num)
  653. }
  654. //取-符合-发布时间半年内的数据
  655. if util.IntAll(tmp["dataging"]) == 1 {
  656. pubtime := util.Int64All(tmp["publishtime"])
  657. if pubtime > 0 && pubtime >= between_time {
  658. oknum++
  659. if deterTime==0 {
  660. log.Println("找到第一条符合条件的数据")
  661. deterTime = util.Int64All(tmp["publishtime"])
  662. dayArr = append(dayArr,tmp)
  663. }else {
  664. if pubtime-deterTime >timingSpanDay*86400 {
  665. //新数组重新构建,当前组数据加到全部组数据
  666. pendAllArr = append(pendAllArr,dayArr)
  667. dayArr = []map[string]interface{}{}
  668. deterTime = util.Int64All(tmp["publishtime"])
  669. dayArr = append(dayArr,tmp)
  670. }else {
  671. dayArr = append(dayArr,tmp)
  672. }
  673. }
  674. }else {
  675. //不在两年内的也清标记
  676. updateExtract = append(updateExtract, []map[string]interface{}{
  677. map[string]interface{}{
  678. "_id": tmp["_id"],
  679. },
  680. map[string]interface{}{
  681. "$set": map[string]interface{}{
  682. "dataging": 0,
  683. },
  684. },
  685. })
  686. if len(updateExtract) > 50 {
  687. mgo.UpSertBulk(extract, updateExtract...)
  688. updateExtract = [][]map[string]interface{}{}
  689. }
  690. }
  691. }
  692. tmp = make(map[string]interface{})
  693. }
  694. //批量更新标记
  695. if len(updateExtract) > 0 {
  696. mgo.UpSertBulk(extract, updateExtract...)
  697. updateExtract = [][]map[string]interface{}{}
  698. }
  699. if len(dayArr)>0 {
  700. pendAllArr = append(pendAllArr,dayArr)
  701. dayArr = []map[string]interface{}{}
  702. }
  703. log.Println("查询数量:",num,"符合条件:",oknum)
  704. if len(pendAllArr) <= 0 {
  705. log.Println("没找到dataging==1的数据")
  706. return
  707. }
  708. //测试分组数量是否正确
  709. testNum:=0
  710. for k,v:=range pendAllArr {
  711. log.Println("第",k,"组--","数量:",len(v))
  712. testNum = testNum+len(v)
  713. }
  714. log.Println("本地构建分组完成:",len(pendAllArr),"组","测试-总计数量:",testNum)
  715. n, repeateN := 0, 0
  716. for k,v:=range pendAllArr {
  717. //构建当前组的数据池
  718. log.Println("构建第",k,"组---(数据池)")
  719. DM = TimedTaskDatamap(dupdays, util.Int64All(v[0]["publishtime"]))
  720. log.Println("开始遍历判重第",k,"组 共计数量:",len(v))
  721. n = n+len(v)
  722. log.Println("统计目前总数量:",n,"重复数量:",repeateN)
  723. for _,tmp:=range v {
  724. info := NewInfo(tmp)
  725. if !LowHeavy { //是否进行低质量数据判重
  726. if invalidData(info.buyer, info.projectname, info.projectcode, info.contractnumber) {
  727. log.Println("无效数据")
  728. updateExtract = append(updateExtract, []map[string]interface{}{
  729. map[string]interface{}{
  730. "_id": tmp["_id"],
  731. },
  732. map[string]interface{}{
  733. "$set": map[string]interface{}{
  734. "repeat": -1, //无效数据标签
  735. "dataging": 0,
  736. },
  737. },
  738. })
  739. if len(updateExtract) > 50 {
  740. mgo.UpSertBulk(extract, updateExtract...)
  741. updateExtract = [][]map[string]interface{}{}
  742. }
  743. continue
  744. }
  745. }
  746. b, source, reason := DM.check(info)
  747. if b { //有重复,生成更新语句,更新抽取和更新招标
  748. log.Println("判重结果", b, reason,"目标id",info.id)
  749. repeateN++
  750. //重复数据打标签
  751. updateExtract = append(updateExtract, []map[string]interface{}{
  752. map[string]interface{}{
  753. "_id": tmp["_id"],
  754. },
  755. map[string]interface{}{
  756. "$set": map[string]interface{}{
  757. "repeat": 1,
  758. "repeat_reason": reason,
  759. "repeat_id": source.id,
  760. "dataging": 0,
  761. },
  762. },
  763. })
  764. }else {
  765. updateExtract = append(updateExtract, []map[string]interface{}{
  766. map[string]interface{}{
  767. "_id": tmp["_id"],
  768. },
  769. map[string]interface{}{
  770. "$set": map[string]interface{}{
  771. "dataging": 0,//符合条件的都为dataging==0
  772. },
  773. },
  774. })
  775. }
  776. if len(updateExtract) > 50 {
  777. mgo.UpSertBulk(extract, updateExtract...)
  778. updateExtract = [][]map[string]interface{}{}
  779. }
  780. }
  781. }
  782. if len(updateExtract) > 0 {
  783. mgo.UpSertBulk(extract, updateExtract...)
  784. updateExtract = [][]map[string]interface{}{}
  785. }
  786. log.Println("this timeTask over.", n, "repeateN:", repeateN)
  787. //任务完成,开始发送广播通知下面节点 发udp 去升索引待定 + 合并
  788. if n > repeateN {
  789. for _, to := range nextNode {
  790. next_sid := util.BsonIdToSId(task_sid)
  791. next_eid := util.BsonIdToSId(task_eid)
  792. key := next_sid + "-" + next_eid + "-" + util.ObjToString(to["stype"])
  793. by, _ := json.Marshal(map[string]interface{}{
  794. "gtid": next_sid,
  795. "lteid": next_eid,
  796. "stype": util.ObjToString(to["stype"]),
  797. "key": key,
  798. })
  799. addr := &net.UDPAddr{
  800. IP: net.ParseIP(to["addr"].(string)),
  801. Port: util.IntAll(to["port"]),
  802. }
  803. node := &udpNode{by, addr, time.Now().Unix(), 0}
  804. udptaskmap.Store(key, node)
  805. udpclient.WriteUdp(by, mu.OP_TYPE_DATA, addr)
  806. }
  807. }
  808. }
  809. //合并字段-并更新merge字段的值
  810. func mergeDataFields(source *Info, info *Info) (*Info, []int64, bool) {
  811. merge_recordMap := make(map[string]interface{}, 0)
  812. mergeArr := make([]int64, 0)
  813. //是否替换数据了-记录原始的数据
  814. is_replace := false
  815. //1、城市
  816. if source.area == "" || source.area == "全国" {
  817. //为空
  818. if info.area != "全国" && info.area != "" {
  819. merge_recordMap["area"] = source.area
  820. merge_recordMap["city"] = source.city
  821. source.area = info.area
  822. source.city = info.city
  823. mergeArr = append(mergeArr, 1)
  824. is_replace = true
  825. }
  826. } else {
  827. //不为空-查看站点相关-有值必替换
  828. if source.is_site {
  829. //是站点替换的城市
  830. merge_recordMap["site_area"] = source.area
  831. merge_recordMap["site_city"] = source.city
  832. mergeArr = append(mergeArr, 0)
  833. is_replace = true
  834. source.is_site = false
  835. }
  836. }
  837. //2、项目名称
  838. if source.projectname == "" && info.projectname != "" {
  839. merge_recordMap["projectname"] = source.projectname
  840. source.projectname = info.projectname
  841. mergeArr = append(mergeArr, 2)
  842. is_replace = true
  843. }
  844. //3、项目编号
  845. if source.projectcode == "" && info.projectcode != "" {
  846. merge_recordMap["projectcode"] = source.projectcode
  847. source.projectcode = info.projectcode
  848. mergeArr = append(mergeArr, 3)
  849. is_replace = true
  850. }
  851. //4、采购单位
  852. if source.buyer == "" && info.buyer != "" {
  853. merge_recordMap["buyer"] = source.buyer
  854. source.buyer = info.buyer
  855. mergeArr = append(mergeArr, 4)
  856. is_replace = true
  857. }
  858. //5、预算
  859. if source.budget == 0 && info.budget != 0 {
  860. merge_recordMap["budget"] = source.budget
  861. source.budget = info.budget
  862. mergeArr = append(mergeArr, 5)
  863. is_replace = true
  864. }
  865. //6、中标单位
  866. if source.winner == "" && info.winner != "" {
  867. merge_recordMap["winner"] = source.winner
  868. source.winner = info.winner
  869. mergeArr = append(mergeArr, 6)
  870. is_replace = true
  871. }
  872. //7、中标金额
  873. if source.bidamount == 0 && info.bidamount != 0 {
  874. merge_recordMap["bidamount"] = source.bidamount
  875. source.bidamount = info.bidamount
  876. mergeArr = append(mergeArr, 7)
  877. is_replace = true
  878. }
  879. //8、开标时间-地点
  880. if source.bidopentime == 0 && info.bidopentime != 0 {
  881. merge_recordMap["bidopentime"] = source.bidopentime
  882. source.bidopentime = info.bidopentime
  883. mergeArr = append(mergeArr, 8)
  884. is_replace = true
  885. }
  886. //9、合同编号
  887. if source.contractnumber == "" && info.contractnumber != "" {
  888. merge_recordMap["contractnumber"] = source.contractnumber
  889. source.contractnumber = info.contractnumber
  890. mergeArr = append(mergeArr, 9)
  891. is_replace = true
  892. }
  893. //10、发布时间
  894. if source.publishtime == 0 && info.publishtime != 0 {
  895. merge_recordMap["publishtime"] = source.publishtime
  896. source.publishtime = info.publishtime
  897. mergeArr = append(mergeArr, 10)
  898. is_replace = true
  899. }
  900. //11、代理机构
  901. if source.agency == "" && info.agency != "" {
  902. merge_recordMap["agency"] = source.agency
  903. source.agency = info.agency
  904. mergeArr = append(mergeArr, 11)
  905. is_replace = true
  906. }
  907. if is_replace { //有过替换更新
  908. //总次数+1
  909. source.mergemap["total_num"] = util.Int64All(source.mergemap["total_num"]) + 1
  910. merge_recordMap["num"] = util.Int64All(source.mergemap["total_num"])
  911. //和哪一个数据id进行非空替换的-记录
  912. key := info.id
  913. source.mergemap[key] = merge_recordMap
  914. }
  915. //待进一步优化
  916. return source, mergeArr, is_replace
  917. }
  918. //权重评估
  919. func basicDataScore(v *Info, info *Info) bool {
  920. /*
  921. 权重评估
  922. 网站优先级判定规则:
  923. 1、中央>省>市>县区
  924. 2、政府采购>公共资源>采购单位官网>招标代理公司/平台
  925. */
  926. v_score, info_score := -1, -1
  927. dict_v := SiteMap[v.site]
  928. dict_info := SiteMap[info.site]
  929. //先判断level
  930. if dict_v != nil {
  931. v_level := util.ObjToString(dict_v["level"])
  932. if v_level == "中央" {
  933. v_score = 4
  934. } else if v_level == "省级" {
  935. v_score = 3
  936. } else if v_level == "市级" {
  937. v_score = 2
  938. } else if v_level == "县区" {
  939. v_score = 1
  940. } else if v_level == "" {
  941. } else {
  942. v_score = 0
  943. }
  944. }
  945. if dict_info != nil {
  946. info_level := util.ObjToString(dict_info["level"])
  947. if info_level == "中央" {
  948. info_score = 4
  949. } else if info_level == "省级" {
  950. info_score = 3
  951. } else if info_level == "市级" {
  952. info_score = 2
  953. } else if info_level == "县区" {
  954. info_score = 1
  955. } else if info_level == "" {
  956. } else {
  957. v_score = 0
  958. }
  959. }
  960. if v_score > info_score {
  961. return true
  962. }
  963. if v_score < info_score {
  964. return false
  965. }
  966. //判断sitetype
  967. if dict_v != nil {
  968. v_sitetype := util.ObjToString(dict_v["sitetype"])
  969. if v_sitetype == "政府采购" || v_sitetype == "政府门户" {
  970. v_score = 4
  971. } else if v_sitetype == "公共资源" {
  972. v_score = 3
  973. } else if v_sitetype == "官方网站" {
  974. v_score = 2
  975. } else if v_sitetype == "社会公共招标平台" || v_sitetype == "企业招标平台" {
  976. v_score = 1
  977. } else if v_sitetype == "" {
  978. } else {
  979. v_score = 0
  980. }
  981. }
  982. if dict_info != nil {
  983. info_sitetype := util.ObjToString(dict_info["sitetype"])
  984. if info_sitetype == "政府采购" || info_sitetype == "政府门户" {
  985. info_score = 4
  986. } else if info_sitetype == "公共资源" {
  987. info_score = 3
  988. } else if info_sitetype == "官方网站" {
  989. info_score = 2
  990. } else if info_sitetype == "社会公共招标平台" || info_sitetype == "企业招标平台" {
  991. info_score = 1
  992. } else if info_sitetype == "" {
  993. } else {
  994. info_score = 0
  995. }
  996. }
  997. if v_score > info_score {
  998. return true
  999. }
  1000. if v_score < info_score {
  1001. return false
  1002. }
  1003. //网站评估
  1004. m, n := 0, 0
  1005. if v.projectname != "" {
  1006. m++
  1007. }
  1008. if v.buyer != "" {
  1009. m++
  1010. }
  1011. if v.projectcode != "" || v.contractnumber != "" {
  1012. m++
  1013. }
  1014. if v.budget != 0 {
  1015. m++
  1016. }
  1017. if v.bidamount != 0 {
  1018. m++
  1019. }
  1020. if v.winner != "" {
  1021. m++
  1022. }
  1023. if v.bidopentime != 0 {
  1024. m++
  1025. }
  1026. if v.bidopenaddress != "" {
  1027. m++
  1028. }
  1029. if v.agency != "" {
  1030. m = m + 2
  1031. }
  1032. if v.city != "" {
  1033. m = m + 2
  1034. }
  1035. if info.projectname != "" {
  1036. n++
  1037. }
  1038. if info.buyer != "" {
  1039. n++
  1040. }
  1041. if info.projectcode != "" || info.contractnumber != "" {
  1042. n++
  1043. }
  1044. if info.budget != 0 {
  1045. n++
  1046. }
  1047. if info.bidamount != 0 {
  1048. n++
  1049. }
  1050. if info.winner != "" {
  1051. n++
  1052. }
  1053. if info.bidopentime != 0 {
  1054. n++
  1055. }
  1056. if info.bidopenaddress != "" {
  1057. n++
  1058. }
  1059. if info.agency != "" {
  1060. n = n + 2
  1061. }
  1062. if info.city != "" {
  1063. n = n + 2
  1064. }
  1065. if m > n {
  1066. return true
  1067. } else if m == n {
  1068. if v.publishtime >= info.publishtime {
  1069. return true
  1070. } else {
  1071. return false
  1072. }
  1073. } else {
  1074. return false
  1075. }
  1076. }
  1077. //无效数据
  1078. func invalidData(d1 string, d2 string, d3 string, d4 string) bool {
  1079. var n int
  1080. if d1 != "" {
  1081. n++
  1082. }
  1083. if d2 != "" {
  1084. n++
  1085. }
  1086. if d3 != "" {
  1087. n++
  1088. }
  1089. if d4 != "" {
  1090. n++
  1091. }
  1092. if n == 0 {
  1093. return true
  1094. }
  1095. return false
  1096. }
  1097. //迁移数据dupdays+5之前的数据
  1098. func movedata() {
  1099. sess := mgo.GetMgoConn()
  1100. defer mgo.DestoryMongoConn(sess)
  1101. year, month, day := time.Now().Date()
  1102. q := map[string]interface{}{
  1103. "comeintime": map[string]interface{}{
  1104. "$lt": time.Date(year, month, day, 0, 0, 0, 0, time.Local).Add(-time.Duration(dupdays) * 24 * time.Hour).Unix(),
  1105. },
  1106. }
  1107. log.Println(q)
  1108. it := sess.DB(mgo.DbName).C(extract).Find(&q).Iter()
  1109. index := 0
  1110. for tmp := make(map[string]interface{}); it.Next(&tmp); index++ {
  1111. mgo.Save(extract_back, tmp)
  1112. tmp = map[string]interface{}{}
  1113. if index%1000 == 0 {
  1114. log.Println("index", index)
  1115. }
  1116. }
  1117. log.Println("save to", extract_back, " ok index", index)
  1118. delnum := mgo.Delete(extract, q)
  1119. log.Println("remove from ", extract, delnum)
  1120. }