elasticutil.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955
  1. package elastic
  2. import (
  3. "os"
  4. "runtime"
  5. "sync"
  6. "time"
  7. // "bytes"
  8. "encoding/json"
  9. "fmt"
  10. "log"
  11. "qfw/util"
  12. "qfw/util/mongodb"
  13. mongodbutil "qfw/util/mongodbutil"
  14. "reflect"
  15. es "gopkg.in/olivere/elastic.v1"
  16. "strconv"
  17. "strings"
  18. )
  19. //检索库服务地址
  20. var addrs []string
  21. var LocCity = map[string]string{}
  22. var SIZE = 30
  23. const (
  24. QStr = `{"query":{"bool":{"must":[$and],"must_not":[],
  25. "should":[$or],"minimum_should_match" : 1}}}`
  26. )
  27. var pool chan *es.Client
  28. var ntimeout int
  29. var syncPool sync.Pool
  30. //初始化全文检索
  31. func InitElastic(addr string) {
  32. InitElasticSize(addr, SIZE)
  33. map2 := []map[string]interface{}{}
  34. util.ReadConfig("./city.json", &map2)
  35. if len(map2) == 34 {
  36. log.Println("正确")
  37. } else {
  38. log.Println("解析出错!!")
  39. os.Exit(0)
  40. }
  41. Loop(map2, &LocCity)
  42. }
  43. //自定义HttpClient
  44. /**
  45. var httpclient = &http.Client{Transport: &http.Transport{
  46. Dial: func(netw, addr string) (net.Conn, error) {
  47. deadline := time.Now().Add(5000 * time.Millisecond)
  48. c, err := net.DialTimeout(netw, addr, 10000*time.Millisecond)
  49. if err != nil {
  50. return nil, err
  51. }
  52. tcp_conn := c.(*net.TCPConn)
  53. tcp_conn.SetKeepAlive(false)
  54. tcp_conn.SetDeadline(deadline)
  55. return tcp_conn, nil
  56. },
  57. DisableKeepAlives: true, //不保持,这样才能释放
  58. }}
  59. **/
  60. //var op = es.SetHttpClient(httpclient)
  61. func InitElasticSize(addr string, size int) {
  62. pool = make(chan *es.Client, size)
  63. for _, s := range strings.Split(addr, ",") {
  64. addrs = append(addrs, s)
  65. }
  66. for i := 0; i < size; i++ {
  67. client, _ := es.NewClient(es.SetURL(addrs...), es.SetMaxRetries(2), es.SetSniff(false))
  68. pool <- client
  69. }
  70. }
  71. //关闭连接
  72. func DestoryEsConn(client *es.Client) {
  73. pool <- client
  74. }
  75. //获取连接
  76. func GetEsConn() (c *es.Client) {
  77. select {
  78. case c = <-pool:
  79. if c == nil || !c.IsRunning() {
  80. client, err := es.NewClient(es.SetURL(addrs...),
  81. es.SetMaxRetries(2), es.SetSniff(false))
  82. if err == nil && client.IsRunning() {
  83. return client
  84. }
  85. return nil
  86. }
  87. return
  88. case <-time.After(time.Second * 7):
  89. //超时
  90. ntimeout++
  91. log.Println("timeout times:", ntimeout)
  92. return nil
  93. }
  94. }
  95. //保存对象
  96. func Save(index, itype string, obj interface{}) bool {
  97. client := GetEsConn()
  98. defer DestoryEsConn(client)
  99. defer func() {
  100. if r := recover(); r != nil {
  101. log.Println("[E]", r)
  102. for skip := 1; ; skip++ {
  103. _, file, line, ok := runtime.Caller(skip)
  104. if !ok {
  105. break
  106. }
  107. go log.Printf("%v,%v\n", file, line)
  108. }
  109. }
  110. }()
  111. _, err := client.Index().Index(index).Type(itype).BodyJson(util.ObjToMap(obj)).Do()
  112. if err != nil {
  113. log.Println("保存到ES出错", err.Error(), obj)
  114. return false
  115. } else {
  116. return true
  117. }
  118. }
  119. //通用查询
  120. //{"query": {"bool":{"must":[{"query_string":{"default_field":"name","query":"*"}}]}}}
  121. //{"query":{"bool":{"must":{"match":{"content":{"query":"fulltextsearch","operator":"and"}}},"should":[{"match":{"content":{"query":"Elasticsearch","boost":3}}},{"match":{"content":{"query":"Lucene","boost":2}}}]}}}
  122. //prefix
  123. //{"query":{"match":{"title":{"query":"brownfox","operator":"and"}}}} //默认为or
  124. //{"query":{"multi_match":{"query":"PolandStreetW1V","type":"most_fields","fields":["*_street","city^2","country","postcode"]}}}
  125. //{"query":{"wildcard":{"postcode":"W?F*HW"}}}
  126. //{"query":{"regexp":{"postcode":"W[0-9].+"}}}
  127. //{"query":{"filtered":{"filter":{"range":{"price":{"gte":10000}}}}},"aggs":{"single_avg_price":{"avg":{"field":"price"}}}}
  128. //{"query":{"match":{"make":"ford"}},"aggs":{"colors":{"terms":{"field":"color"}}}}//查fork有几种颜色
  129. //过滤器不会计算相关度的得分,所以它们在计算上更快一些
  130. //{"query":{"filtered":{"query":{"match_all":{}},"filter":{"range":{"balance":{"gte":20000,"lte":30000}}}}}}
  131. //{"query":{"match_all":{}},"from":10,"size":10,"_source":["account_number","balance"],"sort":{"balance":{"order":"desc"}}}
  132. //{"query":{"match_phrase":{"address":"milllane"}}}和match不同会去匹配整个短语,相当于must[]
  133. func Get(index, itype, query string) *[]map[string]interface{} {
  134. log.Println("query -- ", query)
  135. client := GetEsConn()
  136. defer DestoryEsConn(client)
  137. var res []map[string]interface{}
  138. if client != nil {
  139. defer func() {
  140. if r := recover(); r != nil {
  141. log.Println("[E]", r)
  142. for skip := 1; ; skip++ {
  143. _, file, line, ok := runtime.Caller(skip)
  144. if !ok {
  145. break
  146. }
  147. go log.Printf("%v,%v\n", file, line)
  148. }
  149. }
  150. }()
  151. searchResult, err := client.Search().Index(index).Type(itype).Source(query).Do()
  152. if err != nil {
  153. log.Println("从ES查询出错", err.Error())
  154. return nil
  155. }
  156. if searchResult.Hits != nil {
  157. resNum := len(searchResult.Hits.Hits)
  158. if resNum < 5000 {
  159. res = make([]map[string]interface{}, resNum)
  160. for i, hit := range searchResult.Hits.Hits {
  161. //d := json.NewDecoder(bytes.NewBuffer(*hit.Source))
  162. //d.UseNumber()
  163. //d.Decode(&res[i])
  164. json.Unmarshal(*hit.Source, &res[i])
  165. }
  166. } else {
  167. log.Println("查询结果太多,查询到:", resNum, "条")
  168. }
  169. }
  170. }
  171. return &res
  172. }
  173. func GetNoLimit(index, itype, query string) *[]map[string]interface{} {
  174. //log.Println("query -- ", query)
  175. client := GetEsConn()
  176. defer DestoryEsConn(client)
  177. var res []map[string]interface{}
  178. if client != nil {
  179. defer func() {
  180. if r := recover(); r != nil {
  181. log.Println("[E]", r)
  182. for skip := 1; ; skip++ {
  183. _, file, line, ok := runtime.Caller(skip)
  184. if !ok {
  185. break
  186. }
  187. go log.Printf("%v,%v\n", file, line)
  188. }
  189. }
  190. }()
  191. searchResult, err := client.Search().Index(index).Type(itype).Source(query).Do()
  192. if err != nil {
  193. log.Println("从ES查询出错", err.Error())
  194. return nil
  195. }
  196. if searchResult.Hits != nil {
  197. resNum := len(searchResult.Hits.Hits)
  198. res = make([]map[string]interface{}, resNum)
  199. for i, hit := range searchResult.Hits.Hits {
  200. json.Unmarshal(*hit.Source, &res[i])
  201. }
  202. }
  203. }
  204. return &res
  205. }
  206. //分页查询
  207. //{"name":"张三","$and":[{"age":{"$gt":10}},{"age":{"$lte":20}}]}
  208. //fields直接是 `"_id","title"`
  209. func GetPage(index, itype, query, order, field string, start, limit int) *[]map[string]interface{} {
  210. return Get(index, itype, MakeQuery(query, order, field, start, limit))
  211. }
  212. var SR = strings.Replace
  213. func MakeQuery(query, order, fileds string, start, limit int) string {
  214. res := AnalyQuery(query, "", QStr)
  215. if len(res) > 10 {
  216. res = SR(SR(SR(SR(res, ",$and", "", -1), "$and", "", -1), ",$or", "", -1), "$or", "", -1)
  217. if len(fileds) > 0 {
  218. //"_source":["account_number","balance"]
  219. res = res[:len(res)-1] + `,"_source":[` + fileds + "]}"
  220. }
  221. //{"name":-1,"age":1}
  222. if len(order) > 0 {
  223. res = res[:len(res)-1] + `,"sort":[` + SR(SR(SR(SR(order, ",", "},{", -1), " ", "", -1), ":-1", `:"desc"`, -1), ":1", `:"asc"`, -1) + `]}`
  224. }
  225. if start > -1 {
  226. res = res[:len(res)-1] + `,"from":` + strconv.Itoa(start) + `,"size":` + strconv.Itoa(limit) + "}"
  227. }
  228. return res
  229. }
  230. return ""
  231. }
  232. //{"name":"aaa"}
  233. func AnalyQuery(query interface{}, parent string, result string) string {
  234. m := make(map[string]interface{})
  235. if q1, ok := query.(string); ok {
  236. json.Unmarshal([]byte(q1), &m)
  237. } else if q2, ok2 := query.(map[string]interface{}); ok2 {
  238. m = q2
  239. }
  240. if len(parent) == 0 {
  241. for k, v := range m {
  242. if k == "$and" || k == "$or" {
  243. temps := ""
  244. if map1, ok := v.([]interface{}); ok {
  245. for i := 0; i < len(map1); i++ {
  246. temps += "," + AnalyQuery(map1[i], k, "")
  247. }
  248. }
  249. if len(temps) > 0 {
  250. temps = temps[1:]
  251. }
  252. result = SR(result, k, temps+","+k, 1)
  253. } else {
  254. switch reflect.TypeOf(v).String() {
  255. case "string":
  256. if strings.Index(k, "TERM_") == 0 {
  257. result = SR(result, "$and", `{"term":{"`+SR(k, "TERM_", "", 1)+`":"`+fmt.Sprintf("%v", v)+`"}},$and`, 1)
  258. } else {
  259. result = SR(result, "$and", `{"query_string":{"default_field":"`+k+`","query":"`+fmt.Sprintf("%v", v)+`"}},$and`, 1)
  260. }
  261. case "int", "int8", "int32", "int64", "float32", "float64":
  262. if strings.Index(k, "TERM_") == 0 {
  263. result = SR(result, "$and", `{"term":{"`+SR(k, "TERM_", "", 1)+`":`+fmt.Sprintf("%v", v)+`}},$and`, 1)
  264. } else {
  265. result = SR(result, "$and", `{"query_string":{"default_field":"`+k+`","query":`+fmt.Sprintf("%v", v)+`}},$and`, 1)
  266. }
  267. default:
  268. result = SR(result, "$and", AnalyQuery(v, k, "")+",$and", 1)
  269. }
  270. }
  271. }
  272. return result
  273. } else {
  274. for k, v := range m {
  275. if k == "$in" {
  276. s := ""
  277. if map1, ok := v.([]interface{}); ok {
  278. for i := 0; i < len(map1); i++ {
  279. s += "," + `"` + fmt.Sprintf("%v", map1[i]) + `"`
  280. }
  281. }
  282. if len(s) > 0 {
  283. s = s[1:]
  284. }
  285. return `{"terms":{"` + parent + `":[` + s + `]}}`
  286. } else if strings.Contains(k, "$lt") || strings.Contains(k, "$gt") {
  287. return `{"range":{"` + parent + `":{"` + SR(k, "$", "", 1) + `":` + fmt.Sprintf("%v", v) + `}}}`
  288. } else {
  289. switch reflect.TypeOf(v).String() {
  290. case "string":
  291. if strings.Index(k, "TERM_") == 0 {
  292. return `{"term":{"` + SR(k, "TERM_", "", 1) + `":"` + fmt.Sprintf("%v", v) + `"}}`
  293. } else {
  294. return `{"query_string":{"default_field":"` + k + `","query":"` + fmt.Sprintf("%v", v) + `"}}`
  295. }
  296. case "int", "int8", "int32", "int64", "float32", "float64":
  297. if strings.Index(k, "TERM_") == 0 {
  298. return `{"term":{"` + SR(k, "TERM_", "", 1) + `":` + fmt.Sprintf("%v", v) + `}}`
  299. } else {
  300. return `{"query_string":{"default_field":"` + k + `","query":` + fmt.Sprintf("%v", v) + `}}`
  301. }
  302. default:
  303. return AnalyQuery(v, k, result)
  304. }
  305. }
  306. }
  307. }
  308. return result
  309. }
  310. func GetByIdField(index, itype, id, fields string) *map[string]interface{} {
  311. client := GetEsConn()
  312. defer DestoryEsConn(client)
  313. if client != nil {
  314. defer func() {
  315. if r := recover(); r != nil {
  316. log.Println("[E]", r)
  317. for skip := 1; ; skip++ {
  318. _, file, line, ok := runtime.Caller(skip)
  319. if !ok {
  320. break
  321. }
  322. go log.Printf("%v,%v\n", file, line)
  323. }
  324. }
  325. }()
  326. query := `{"query":{"term":{"_id":"` + id + `"}}`
  327. if len(fields) > 0 {
  328. query = query + `,"_source":[` + fields + `]`
  329. }
  330. query = query + "}"
  331. searchResult, err := client.Search().Index(index).Type(itype).Source(query).Do()
  332. if err != nil {
  333. log.Println("从ES查询出错", err.Error())
  334. return nil
  335. }
  336. var res map[string]interface{}
  337. if searchResult.Hits != nil {
  338. resNum := len(searchResult.Hits.Hits)
  339. if resNum == 1 {
  340. res = make(map[string]interface{})
  341. for _, hit := range searchResult.Hits.Hits {
  342. json.Unmarshal(*hit.Source, &res)
  343. }
  344. return &res
  345. } else {
  346. log.Println("查询结果太多,查询到:", resNum, "条")
  347. }
  348. }
  349. }
  350. return nil
  351. }
  352. //根据id来查询文档
  353. func GetById(index, itype string, ids ...string) *[]map[string]interface{} {
  354. client := GetEsConn()
  355. defer DestoryEsConn(client)
  356. var res []map[string]interface{}
  357. if client != nil {
  358. defer func() {
  359. if r := recover(); r != nil {
  360. log.Println("[E]", r)
  361. for skip := 1; ; skip++ {
  362. _, file, line, ok := runtime.Caller(skip)
  363. if !ok {
  364. break
  365. }
  366. go log.Printf("%v,%v\n", file, line)
  367. }
  368. }
  369. }()
  370. query := es.NewIdsQuery().Ids(ids...)
  371. searchResult, err := client.Search().Index(index).Type(itype).Query(&query).Do()
  372. if err != nil {
  373. log.Println("从ES查询出错", err.Error())
  374. return nil
  375. }
  376. if searchResult.Hits != nil {
  377. resNum := len(searchResult.Hits.Hits)
  378. if resNum < 5000 {
  379. res = make([]map[string]interface{}, resNum)
  380. for i, hit := range searchResult.Hits.Hits {
  381. json.Unmarshal(*hit.Source, &res[i])
  382. }
  383. } else {
  384. log.Println("查询结果太多,查询到:", resNum, "条")
  385. }
  386. }
  387. }
  388. return &res
  389. }
  390. //删除某个索引,根据查询
  391. func Del(index, itype string, query interface{}) bool {
  392. client := GetEsConn()
  393. defer DestoryEsConn(client)
  394. b := false
  395. if client != nil {
  396. defer func() {
  397. if r := recover(); r != nil {
  398. log.Println("[E]", r)
  399. for skip := 1; ; skip++ {
  400. _, file, line, ok := runtime.Caller(skip)
  401. if !ok {
  402. break
  403. }
  404. go log.Printf("%v,%v\n", file, line)
  405. }
  406. }
  407. }()
  408. var err error
  409. if qs, ok := query.(string); ok {
  410. temp := es.BoolQuery{
  411. QueryStrings: qs,
  412. }
  413. _, err = client.DeleteByQuery().Index(index).Type(itype).Query(temp).Do()
  414. } else if qi, ok2 := query.(es.Query); ok2 {
  415. _, err = client.DeleteByQuery().Index(index).Type(itype).Query(qi).Do()
  416. }
  417. if err != nil {
  418. log.Println("删除索引出错:", err.Error())
  419. } else {
  420. b = true
  421. }
  422. }
  423. return b
  424. }
  425. //根据语句更新对象
  426. func Update(index, itype, id string, updateStr string) bool {
  427. client := GetEsConn()
  428. defer DestoryEsConn(client)
  429. b := false
  430. if client != nil {
  431. defer func() {
  432. if r := recover(); r != nil {
  433. log.Println("[E]", r)
  434. for skip := 1; ; skip++ {
  435. _, file, line, ok := runtime.Caller(skip)
  436. if !ok {
  437. break
  438. }
  439. go log.Printf("%v,%v\n", file, line)
  440. }
  441. }
  442. }()
  443. var err error
  444. _, err = client.Update().Index(index).Type(itype).Id(id).Script(updateStr).ScriptLang("groovy").Do()
  445. if err != nil {
  446. log.Println("更新检索出错:", err.Error())
  447. } else {
  448. b = true
  449. }
  450. }
  451. return b
  452. }
  453. func BulkUpdate(index, itype string, ids []string, updateStr string) {
  454. client := GetEsConn()
  455. defer DestoryEsConn(client)
  456. if client != nil {
  457. defer func() {
  458. if r := recover(); r != nil {
  459. log.Println("[E]", r)
  460. for skip := 1; ; skip++ {
  461. _, file, line, ok := runtime.Caller(skip)
  462. if !ok {
  463. break
  464. }
  465. go log.Printf("%v,%v\n", file, line)
  466. }
  467. }
  468. }()
  469. for _, id := range ids {
  470. _, err := client.Update().Index(index).Type(itype).Id(id).Script(updateStr).ScriptLang("groovy").Do()
  471. if err != nil {
  472. log.Println("更新检索出错:", err.Error())
  473. }
  474. }
  475. }
  476. }
  477. //根据id删除索引对象
  478. func DelById(index, itype, id string) bool {
  479. client := GetEsConn()
  480. defer DestoryEsConn(client)
  481. b := false
  482. if client != nil {
  483. defer func() {
  484. if r := recover(); r != nil {
  485. log.Println("[E]", r)
  486. for skip := 1; ; skip++ {
  487. _, file, line, ok := runtime.Caller(skip)
  488. if !ok {
  489. break
  490. }
  491. go log.Printf("%v,%v\n", file, line)
  492. }
  493. }
  494. }()
  495. var err error
  496. _, err = client.Delete().Index(index).Type(itype).Id(id).Do()
  497. if err != nil {
  498. log.Println("更新检索出错:", err.Error())
  499. } else {
  500. b = true
  501. }
  502. }
  503. return b
  504. }
  505. //先删除后增
  506. func UpdateNewDoc(index, itype string, obj ...interface{}) bool {
  507. client := GetEsConn()
  508. defer DestoryEsConn(client)
  509. b := false
  510. if client != nil {
  511. defer func() {
  512. if r := recover(); r != nil {
  513. log.Println("[E]", r)
  514. for skip := 1; ; skip++ {
  515. _, file, line, ok := runtime.Caller(skip)
  516. if !ok {
  517. break
  518. }
  519. go log.Printf("%v,%v\n", file, line)
  520. }
  521. }
  522. }()
  523. var err error
  524. for _, v := range obj {
  525. tempObj := util.ObjToMap(v)
  526. id := fmt.Sprintf("%v", (*tempObj)["_id"])
  527. client.Delete().Index(index).Type(itype).Id(id).Do()
  528. _, err = client.Index().Index(index).Type(itype).BodyJson(tempObj).Do()
  529. if err != nil {
  530. log.Println("保存到ES出错", err.Error())
  531. } else {
  532. b = true
  533. }
  534. }
  535. }
  536. return b
  537. }
  538. func UpdateEntDoc(id string) bool {
  539. b := false
  540. map2 := map[string]interface{}{}
  541. util.ReadConfig(&map2)
  542. ent := mongodbutil.FindById("enterprise", map2["entMongodbAlias"].(string), map2["entMongodbName"].(string), id, "")
  543. _ent := mongodb.FindById("enterprise", id, "")
  544. if _ent != nil && len(*_ent) > 0 {
  545. for k, v := range *_ent {
  546. (*ent)[k] = v
  547. }
  548. }
  549. if ent != nil {
  550. b = UpdateNewDoc("enterprise", "enterprise", ConverData(ent))
  551. }
  552. return b
  553. }
  554. //把地市代码转为地市
  555. func getLoc(code string, res *map[string]string) (loc string) {
  556. switch len(code) {
  557. case 6:
  558. loc = (*res)[code[:2]] + " " + (*res)[code[:4]] + " " + (*res)[code]
  559. break
  560. case 4:
  561. loc = (*res)[code[:2]] + " " + (*res)[code]
  562. break
  563. case 2:
  564. loc = (*res)[code]
  565. break
  566. }
  567. return
  568. }
  569. //把地市代码转为地市
  570. func Loop(m interface{}, res *map[string]string) {
  571. m1, ok := m.([]interface{})
  572. if !ok {
  573. m2, _ := m.([]map[string]interface{})
  574. for i := 0; i < len(m2); i++ {
  575. ms := m2[i]
  576. (*res)[fmt.Sprintf("%1.0f", ms["k"])] = fmt.Sprintf("%s", ms["n"])
  577. s := ms["s"]
  578. if nil != s {
  579. mss, _ := s.([]interface{})
  580. if nil != mss {
  581. Loop(mss, res)
  582. }
  583. }
  584. }
  585. } else {
  586. for i := 0; i < len(m1); i++ {
  587. ms, _ := m1[i].(map[string]interface{})
  588. (*res)[fmt.Sprintf("%1.0f", ms["k"])] = fmt.Sprintf("%s", ms["n"])
  589. s := ms["s"]
  590. if nil != s {
  591. mss, _ := s.([]interface{})
  592. if nil != mss {
  593. Loop(mss, res)
  594. }
  595. }
  596. }
  597. }
  598. }
  599. func ConverData(ent *map[string]interface{}) map[string]interface{} {
  600. tmp := *ent
  601. id64, _ := tmp["ID"].(int64)
  602. ids := fmt.Sprintf("%d", id64)
  603. tmp2 := make(map[string]interface{})
  604. tmp2["ID"] = ids
  605. tmp2["_id"] = tmp["_id"]
  606. tmp2["Area"] = tmp["Area"]
  607. tmp2["LeRep"] = tmp["LeRep"]
  608. tmp2["RegNo"] = tmp["RegNo"]
  609. tmp2["EntType"] = tmp["EntType"]
  610. tmp2["EntName"] = tmp["EntName"]
  611. tmp2["EntTypeName"] = tmp["EntTypeName"]
  612. tmp2["Dom"] = tmp["Dom"]
  613. tmp2["EstDate"] = tmp["EstDate"]
  614. tmp2["OpStateName"] = tmp["OpStateName"]
  615. tmp2["OpScope"] = tmp["OpScope"]
  616. tmp2["OpState"] = tmp["OpState"]
  617. tmp2["s_submitid"] = tmp["s_submitid"]
  618. tmp2["l_submittime"] = tmp["l_submittime"]
  619. tmp2["s_submitname"] = tmp["s_submitname"]
  620. tmp2["RegCapCurName"] = tmp["RegCapCurName"]
  621. //增加营业状态排序
  622. if tmp2["OpState"] == "06" {
  623. tmp2["OpSint"] = true
  624. } else {
  625. tmp2["OpSint"] = false
  626. }
  627. tmp2["OpLocDistrict"] = tmp["OpLocDistrict"]
  628. //增加代码转名称
  629. tmpLoc, _ := tmp["OpLocDistrict"].(string)
  630. tmp2["OpLocDistrictName"] = getLoc(tmpLoc, &LocCity)
  631. tmp2["RecCap"] = tmp["RecCap"]
  632. tmp2["RegCap"] = tmp["RegCap"]
  633. tmp2["IndustryPhy"] = tmp["IndustryPhy"]
  634. tmp2["IndustryPhyName"] = tmp["IndustryPhyName"]
  635. tmp2["RegOrg"] = tmp["RegOrg"]
  636. tmp2["RegOrgName"] = tmp["RegOrgName"]
  637. tmp2["Tel"] = tmp["Tel"]
  638. tmp2["CompForm"] = tmp["CompForm"]
  639. tmp2["CompFormName"] = tmp["CompFormName"]
  640. //增加异常名录标记
  641. Ycml := tmp["Ycml"]
  642. if util.ObjToString(Ycml) == "1" {
  643. tmp2["Ycml"] = true
  644. } else {
  645. tmp2["Ycml"] = false
  646. }
  647. //增加年报联系信息
  648. if tmp["Nb_email"] != nil {
  649. tmp2["Nb_email"] = tmp["Nb_email"]
  650. }
  651. if tmp["Nb_tel"] != nil {
  652. tmp2["Nb_tel"] = tmp["Nb_tel"]
  653. }
  654. if tmp["Nb_addr"] != nil {
  655. tmp2["Nb_addr"] = tmp["Nb_addr"]
  656. }
  657. s_synopsis := tmp["s_synopsis"]
  658. if s_synopsis == nil {
  659. s_synopsis = ""
  660. }
  661. tmp2["s_synopsis"] = s_synopsis //企业简介
  662. //股东
  663. stock := getStock(tmp["investor"])
  664. tmp2["stock"] = stock
  665. tmp2["LegCerNO"] = tmp["LegCerNO"]
  666. if tmp["s_microwebsite"] != nil {
  667. tmp2["s_microwebsite"] = tmp["s_microwebsite"]
  668. }
  669. tmp2["SourceType"] = tmp["SourceType"] //数据来源
  670. s_servicenames := tmp["s_servicenames"]
  671. if s_servicenames == nil {
  672. s_servicenames = ""
  673. }
  674. tmp2["s_servicenames"] = s_servicenames //服务名称
  675. s_action := tmp["s_action"]
  676. if s_action == nil {
  677. s_action = "N"
  678. }
  679. tmp2["s_action"] = s_action
  680. tmp2["s_persion"] = tmp["s_persion"]
  681. tmp2["s_mobile"] = tmp["s_mobile"]
  682. tmp2["s_enturl"] = tmp["s_enturl"]
  683. tmp2["s_weixin"] = tmp["s_weixin"]
  684. tmp2["s_avatar"] = tmp["s_avatar"]
  685. return tmp2
  686. }
  687. func getStock(obj interface{}) string {
  688. stock := ""
  689. if ns, ok := obj.([]interface{}); ok {
  690. stock = " "
  691. for _, ns1 := range ns {
  692. if nn, ok1 := ns1.(map[string]interface{}); ok1 {
  693. tmp := fmt.Sprintf("%s", nn["Inv"])
  694. if strings.Index(stock, tmp) < 0 {
  695. stock += tmp + " "
  696. }
  697. }
  698. }
  699. }
  700. return stock
  701. }
  702. func BulkSave(index, itype string, obj *[]map[string]interface{}, isDelBefore bool) {
  703. client := GetEsConn()
  704. defer DestoryEsConn(client)
  705. if client != nil {
  706. defer func() {
  707. if r := recover(); r != nil {
  708. log.Println("[E]", r)
  709. for skip := 1; ; skip++ {
  710. _, file, line, ok := runtime.Caller(skip)
  711. if !ok {
  712. break
  713. }
  714. go log.Printf("%v,%v\n", file, line)
  715. }
  716. }
  717. }()
  718. req := client.Bulk()
  719. for _, v := range *obj {
  720. if isDelBefore {
  721. req = req.Add(es.NewBulkDeleteRequest().Index(index).Type(itype).Id(fmt.Sprintf("%v", v["_id"])))
  722. }
  723. req = req.Add(es.NewBulkIndexRequest().Index(index).Type(itype).Doc(v))
  724. }
  725. _, err := req.Do()
  726. if err != nil {
  727. log.Println("批量保存到ES出错", err.Error())
  728. }
  729. }
  730. }
  731. func Count(index, itype string, query interface{}) int64 {
  732. client := GetEsConn()
  733. defer DestoryEsConn(client)
  734. if client != nil {
  735. defer func() {
  736. if r := recover(); r != nil {
  737. log.Println("[E]", r)
  738. for skip := 1; ; skip++ {
  739. _, file, line, ok := runtime.Caller(skip)
  740. if !ok {
  741. break
  742. }
  743. go log.Printf("%v,%v\n", file, line)
  744. }
  745. }
  746. }()
  747. var qq es.Query
  748. if qs, ok := query.(string); ok {
  749. temp := es.BoolQuery{
  750. QueryStrings: qs,
  751. }
  752. qq = temp
  753. } else if qi, ok2 := query.(es.Query); ok2 {
  754. qq = qi
  755. }
  756. n, err := client.Count(index).Type(itype).Query(qq).Do()
  757. if err != nil {
  758. log.Println("统计出错", err.Error())
  759. }
  760. return n
  761. }
  762. return 0
  763. }
  764. //ngram精确查询
  765. /*
  766. {
  767. "query": {
  768. "bool": {
  769. "should": [
  770. {
  771. "bool":{
  772. "must":[
  773. { "multi_match": {
  774. "query": "智能",
  775. "type": "phrase",
  776. "fields": [
  777. "title"
  778. ],
  779. "analyzer": "my_ngram"
  780. }
  781. },{
  782. "multi_match": {
  783. "query": "机器",
  784. "type": "phrase",
  785. "fields": [
  786. "title"
  787. ],
  788. "analyzer": "my_ngram"
  789. }
  790. },{
  791. "multi_match": {
  792. "query": "2016",
  793. "type": "phrase",
  794. "fields": [
  795. "title"
  796. ],
  797. "analyzer": "my_ngram"
  798. }
  799. }
  800. ]
  801. }
  802. },
  803. {
  804. "bool":{
  805. "must":[
  806. { "multi_match": {
  807. "query": "河南",
  808. "type": "phrase",
  809. "fields": [
  810. "title"
  811. ],
  812. "analyzer": "my_ngram"
  813. }
  814. },{
  815. "multi_match": {
  816. "query": "工商",
  817. "type": "phrase",
  818. "fields": [
  819. "title"
  820. ],
  821. "analyzer": "my_ngram"
  822. }
  823. },{
  824. "multi_match": {
  825. "query": "2016",
  826. "type": "phrase",
  827. "fields": [
  828. "title"
  829. ],
  830. "analyzer": "my_ngram"
  831. }
  832. }
  833. ]
  834. }
  835. }
  836. ],"minimum_should_match": 1
  837. }
  838. },
  839. "_source": [
  840. "_id",
  841. "title"
  842. ],
  843. "from": 0,
  844. "size": 10,
  845. "sort": [{
  846. "publishtime": "desc"
  847. }]
  848. }
  849. */
  850. //"2016+智能+办公,"河南+工商"
  851. //["2016+智能+办公","河南+工商"]
  852. //QStr = `{"query":{"bool":{should":[$or],"minimum_should_match" : 1}}}`
  853. //{"bool":{"must":[]}}
  854. //{"multi_match": {"query": "$word","type": "phrase", "fields": [$field],"analyzer": "my_ngram"}}
  855. const (
  856. NgramStr = `{"query":{"bool":{"must":[%s],"should":[%s],"minimum_should_match" : 1}}}`
  857. NgramMust = `{"bool":{"must":[%s]}}`
  858. minq = `{"multi_match": {"query": "%s","type": "phrase", "fields": [%s],"analyzer": "my_ngram"}}`
  859. )
  860. func GetNgramQuery(query interface{}, mustquery, findfields string) (qstr string) {
  861. var words []string
  862. if q, ok := query.(string); ok {
  863. words = strings.Split(q, ",")
  864. } else if q, ok := query.([]string); ok {
  865. words = q
  866. } else if q, ok := query.([]interface{}); ok {
  867. words = util.ObjArrToStringArr(q)
  868. }
  869. if words != nil {
  870. new_minq := fmt.Sprintf(minq, "%s", findfields)
  871. musts := []string{}
  872. for _, qs_words := range words {
  873. qws := strings.Split(qs_words, "+")
  874. mq := []string{}
  875. for _, qs_word := range qws {
  876. mq = append(mq, fmt.Sprintf(new_minq, qs_word))
  877. }
  878. musts = append(musts, fmt.Sprintf(NgramMust, strings.Join(mq, ",")))
  879. }
  880. qstr = fmt.Sprintf(NgramStr, mustquery, strings.Join(musts, ","))
  881. log.Println("ngram-query", qstr)
  882. }
  883. return
  884. }
  885. func GetByNgram(index, itype string, query interface{}, mustquery, findfields, order, fields string, start, limit int) *[]map[string]interface{} {
  886. defer util.Catch()
  887. qstr := GetNgramQuery(query, mustquery, findfields)
  888. if qstr != "" {
  889. if len(fields) > 0 {
  890. qstr = qstr[:len(qstr)-1] + `,"_source":[` + fields + "]}"
  891. }
  892. if len(order) > 0 {
  893. qstr = qstr[:len(qstr)-1] + `,"sort":[` + SR(SR(SR(SR(order, ",", "},{", -1), " ", "", -1), ":-1", `:"desc"`, -1), ":1", `:"asc"`, -1) + `]}`
  894. }
  895. if start > -1 {
  896. qstr = qstr[:len(qstr)-1] + `,"from":` + strconv.Itoa(start) + `,"size":` + strconv.Itoa(limit) + "}"
  897. }
  898. log.Println("ngram-find", qstr)
  899. return Get(index, itype, qstr)
  900. } else {
  901. return nil
  902. }
  903. }