elasticSim.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. package elastic
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. es "github.com/olivere/elastic/v7"
  8. util "jygit.jydev.jianyu360.cn/data_processing/common_utils"
  9. "log"
  10. "runtime"
  11. "strings"
  12. "sync"
  13. "time"
  14. )
  15. type Elastic struct {
  16. S_esurl string
  17. I_size int
  18. Addrs []string
  19. Pool chan *es.Client
  20. lastTime int64
  21. lastTimeLock sync.Mutex
  22. ntimeout int
  23. Username string
  24. Password string
  25. }
  26. func (e *Elastic) InitElasticSize() {
  27. e.Pool = make(chan *es.Client, e.I_size)
  28. for _, s := range strings.Split(e.S_esurl, ",") {
  29. e.Addrs = append(e.Addrs, s)
  30. }
  31. for i := 0; i < e.I_size; i++ {
  32. client, _ := es.NewClient(es.SetURL(e.Addrs...), es.SetBasicAuth(e.Username, e.Password), es.SetMaxRetries(2), es.SetSniff(false))
  33. e.Pool <- client
  34. }
  35. }
  36. // 关闭连接
  37. func (e *Elastic) DestoryEsConn(client *es.Client) {
  38. select {
  39. case e.Pool <- client:
  40. break
  41. case <-time.After(time.Second * 1):
  42. if client != nil {
  43. client.Stop()
  44. }
  45. client = nil
  46. }
  47. }
  48. func (e *Elastic) GetEsConn() *es.Client {
  49. select {
  50. case c := <-e.Pool:
  51. if c == nil || !c.IsRunning() {
  52. log.Println("new esclient.", len(e.Pool))
  53. client, err := es.NewClient(es.SetURL(e.Addrs...), es.SetBasicAuth(e.Username, e.Password),
  54. es.SetMaxRetries(2), es.SetSniff(false))
  55. if err == nil && client.IsRunning() {
  56. return client
  57. }
  58. }
  59. return c
  60. case <-time.After(time.Second * 4):
  61. //超时
  62. e.ntimeout++
  63. e.lastTimeLock.Lock()
  64. defer e.lastTimeLock.Unlock()
  65. //12秒后允许创建链接
  66. c := time.Now().Unix() - e.lastTime
  67. if c > 12 {
  68. e.lastTime = time.Now().Unix()
  69. log.Println("add client..", len(e.Pool))
  70. c, _ := es.NewClient(es.SetURL(e.Addrs...), es.SetBasicAuth(e.Username, e.Password), es.SetMaxRetries(2), es.SetSniff(false))
  71. go func() {
  72. for i := 0; i < 2; i++ {
  73. client, _ := es.NewClient(es.SetURL(e.Addrs...), es.SetBasicAuth(e.Username, e.Password), es.SetMaxRetries(2), es.SetSniff(false))
  74. e.Pool <- client
  75. }
  76. }()
  77. return c
  78. }
  79. return nil
  80. }
  81. }
  82. func (e *Elastic) Get(index string, query es.Query) *[]map[string]interface{} {
  83. client := e.GetEsConn()
  84. defer func() {
  85. go e.DestoryEsConn(client)
  86. }()
  87. var res []map[string]interface{}
  88. if client != nil {
  89. defer func() {
  90. if r := recover(); r != nil {
  91. log.Println("[E]", r)
  92. for skip := 1; ; skip++ {
  93. _, file, line, ok := runtime.Caller(skip)
  94. if !ok {
  95. break
  96. }
  97. go log.Printf("%v,%v\n", file, line)
  98. }
  99. }
  100. }()
  101. searchResult, err := client.Search().Index(index).Query(query).Do(context.Background())
  102. if err != nil {
  103. log.Println("从ES查询出错", err.Error())
  104. return nil
  105. }
  106. if searchResult.Hits != nil {
  107. resNum := len(searchResult.Hits.Hits)
  108. if resNum < 5000 {
  109. res = make([]map[string]interface{}, resNum)
  110. for i, hit := range searchResult.Hits.Hits {
  111. parseErr := json.Unmarshal(hit.Source, &res[i])
  112. if parseErr == nil && hit.Highlight != nil && res[i] != nil {
  113. res[i]["highlight"] = map[string][]string(hit.Highlight)
  114. }
  115. }
  116. } else {
  117. log.Println("查询结果太多,查询到:", resNum, "条")
  118. }
  119. }
  120. }
  121. return &res
  122. }
  123. // 关闭elastic
  124. func (e *Elastic) Close() {
  125. for i := 0; i < e.I_size; i++ {
  126. cli := <-e.Pool
  127. cli.Stop()
  128. cli = nil
  129. }
  130. e.Pool = nil
  131. e = nil
  132. }
  133. //获取连接
  134. //func (e *Elastic) GetEsConn() (c *es.Client) {
  135. // defer util.Catch()
  136. // select {
  137. // case c = <-e.Pool:
  138. // if c == nil || !c.IsRunning() {
  139. // client, err := es.NewClient(es.SetURL(addrs...),
  140. // es.SetMaxRetries(2), es.SetSniff(false))
  141. // if err == nil && client.IsRunning() {
  142. // return client
  143. // }
  144. // return nil
  145. // }
  146. // return
  147. // case <-time.After(time.Second * 7):
  148. // //超时
  149. // ntimeout++
  150. // log.Println("timeout times:", ntimeout)
  151. // return nil
  152. // }
  153. //}
  154. func (e *Elastic) BulkSave(index string, obj []map[string]interface{}) {
  155. client := e.GetEsConn()
  156. defer e.DestoryEsConn(client)
  157. if client != nil {
  158. req := client.Bulk()
  159. for _, v := range obj {
  160. //if isDelBefore {
  161. // req = req.Add(es.NewBulkDeleteRequest().Index(index).Id(fmt.Sprintf("%v", v["_id"])))
  162. //}
  163. id := util.ObjToString(v["_id"])
  164. doc := make(map[string]interface{}, 0)
  165. for k, va := range v {
  166. doc[k] = va
  167. }
  168. delete(doc, "_id")
  169. req = req.Add(es.NewBulkIndexRequest().Index(index).Id(id).Doc(doc))
  170. }
  171. _, err := req.Do(context.Background())
  172. if err != nil {
  173. log.Println("批量保存到ES出错", err.Error())
  174. }
  175. }
  176. }
  177. // 根据id删除索引对象
  178. func (e *Elastic) DelById(index, id string) bool {
  179. client := e.GetEsConn()
  180. defer e.DestoryEsConn(client)
  181. b := false
  182. if client != nil {
  183. var err error
  184. _, err = client.Delete().Index(index).Id(id).Do(context.Background())
  185. if err != nil {
  186. log.Println("更新检索出错:", err.Error())
  187. } else {
  188. b = true
  189. }
  190. }
  191. return b
  192. }
  193. func (e *Elastic) GetNoLimit(index, query string) *[]map[string]interface{} {
  194. client := e.GetEsConn()
  195. defer e.DestoryEsConn(client)
  196. var res []map[string]interface{}
  197. if client != nil {
  198. defer func() {
  199. if r := recover(); r != nil {
  200. log.Println("[E]", r)
  201. for skip := 1; ; skip++ {
  202. _, file, line, ok := runtime.Caller(skip)
  203. if !ok {
  204. break
  205. }
  206. go log.Printf("%v,%v\n", file, line)
  207. }
  208. }
  209. }()
  210. searchResult, err := client.Search().Index(index).Source(query).Do(context.Background())
  211. if err != nil {
  212. log.Println("从ES查询出错", err.Error())
  213. return nil
  214. }
  215. if searchResult.Hits != nil {
  216. resNum := len(searchResult.Hits.Hits)
  217. res = make([]map[string]interface{}, resNum)
  218. for i, hit := range searchResult.Hits.Hits {
  219. json.Unmarshal(hit.Source, &res[i])
  220. }
  221. }
  222. }
  223. return &res
  224. }
  225. //func (e *Elastic) GetByIdField(index, itype, id, fields string) *map[string]interface{} {
  226. // client := e.GetEsConn()
  227. // defer e.DestoryEsConn(client)
  228. // if client != nil {
  229. // defer func() {
  230. // if r := recover(); r != nil {
  231. // log.Println("[E]", r)
  232. // for skip := 1; ; skip++ {
  233. // _, file, line, ok := runtime.Caller(skip)
  234. // if !ok {
  235. // break
  236. // }
  237. // go log.Printf("%v,%v\n", file, line)
  238. // }
  239. // }
  240. // }()
  241. // query := `{"query":{"term":{"_id":"` + id + `"}}`
  242. // if len(fields) > 0 {
  243. // query = query + `,"_source":[` + fields + `]`
  244. // }
  245. // query = query + "}"
  246. // searchResult, err := client.Search().Index(index).Type(itype).Source(query).Do()
  247. // if err != nil {
  248. // log.Println("从ES查询出错", err.Error())
  249. // return nil
  250. // }
  251. // var res map[string]interface{}
  252. // if searchResult.Hits != nil {
  253. // resNum := len(searchResult.Hits.Hits)
  254. // if resNum == 1 {
  255. // res = make(map[string]interface{})
  256. // for _, hit := range searchResult.Hits.Hits {
  257. // json.Unmarshal(*hit.Source., &res)
  258. // }
  259. // return &res
  260. // }
  261. // }
  262. // }
  263. // return nil
  264. //}
  265. func (e *Elastic) Count(index string, query interface{}) int64 {
  266. client := e.GetEsConn()
  267. defer e.DestoryEsConn(client)
  268. if client != nil {
  269. defer func() {
  270. if r := recover(); r != nil {
  271. log.Println("[E]", r)
  272. for skip := 1; ; skip++ {
  273. _, file, line, ok := runtime.Caller(skip)
  274. if !ok {
  275. break
  276. }
  277. go log.Printf("%v,%v\n", file, line)
  278. }
  279. }
  280. }()
  281. var qq es.Query
  282. if qi, ok2 := query.(es.Query); ok2 {
  283. qq = qi
  284. }
  285. n, err := client.Count(index).Query(qq).Do(context.Background())
  286. if err != nil {
  287. log.Println("统计出错", err.Error())
  288. }
  289. return n
  290. }
  291. return 0
  292. }
  293. //更新一个字段
  294. //func (e *Elastic) BulkUpdateArr(index, itype string, update []map[string]string) {
  295. // client := e.GetEsConn()
  296. // defer e.DestoryEsConn(client)
  297. // if client != nil {
  298. // defer func() {
  299. // if r := recover(); r != nil {
  300. // log.Println("[E]", r)
  301. // for skip := 1; ; skip++ {
  302. // _, file, line, ok := runtime.Caller(skip)
  303. // if !ok {
  304. // break
  305. // }
  306. // go log.Printf("%v,%v\n", file, line)
  307. // }
  308. // }
  309. // }()
  310. // for _, data := range update {
  311. // id := data["id"]
  312. // updateStr := data["updateStr"]
  313. // if id != "" && updateStr != "" {
  314. // _, err := client.Update().Index(index).Type(itype).Id(id).Script(updateStr).ScriptLang("groovy").Do()
  315. // if err != nil {
  316. // log.Println("更新检索出错:", err.Error())
  317. // }
  318. // } else {
  319. // log.Println("数据错误")
  320. // }
  321. // }
  322. // }
  323. //}
  324. //更新多个字段
  325. //func (e *Elastic) BulkUpdateMultipleFields(index, itype string, arrs [][]map[string]interface{}) {
  326. // client := e.GetEsConn()
  327. // defer e.DestoryEsConn(client)
  328. // if client != nil {
  329. // defer func() {
  330. // if r := recover(); r != nil {
  331. // log.Println("[E]", r)
  332. // for skip := 1; ; skip++ {
  333. // _, file, line, ok := runtime.Caller(skip)
  334. // if !ok {
  335. // break
  336. // }
  337. // go log.Printf("%v,%v\n", file, line)
  338. // }
  339. // }
  340. // }()
  341. // for _, arr := range arrs {
  342. // id := arr[0]["id"].(string)
  343. // update := arr[1]["update"].([]string)
  344. // for _, str := range update {
  345. // _, err := client.Update().Index(index).Type(itype).Id(id).Script(str).ScriptLang("groovy").Do()
  346. // if err != nil {
  347. // log.Println("更新检索出错:", err.Error())
  348. // }
  349. // }
  350. // }
  351. // }
  352. //}
  353. // UpdateBulk 批量修改文档
  354. func (e *Elastic) UpdateBulk(index string, docs ...[]map[string]interface{}) {
  355. client := e.GetEsConn()
  356. defer e.DestoryEsConn(client)
  357. bulkService := client.Bulk().Index(index).Refresh("true")
  358. //bulkService.Type(itype)
  359. for _, d := range docs {
  360. id := d[0]["_id"].(string)
  361. doc := es.NewBulkUpdateRequest().Id(id).Doc(d[1])
  362. bulkService.Add(doc)
  363. }
  364. _, err := bulkService.Do(context.Background())
  365. if err != nil {
  366. fmt.Printf("UpdateBulk all success err is %v\n", err)
  367. }
  368. //if len(res.Failed()) > 0 {
  369. // fmt.Printf("UpdateBulk all success failed is %v\n", (res.Items[0]))
  370. //}
  371. }
  372. // UpsertBulk 批量修改文档(不存在则插入)
  373. func (e *Elastic) UpsertBulk(ctx context.Context, index string, ids []string, docs []interface{}) error {
  374. client := e.GetEsConn()
  375. defer e.DestoryEsConn(client)
  376. bulkService := client.Bulk().Index(index).Refresh("true")
  377. //bulkService.Type("bidding")
  378. for i := range ids {
  379. doc := es.NewBulkUpdateRequest().Id(ids[i]).Doc(docs[i]).Upsert(docs[i])
  380. bulkService.Add(doc)
  381. }
  382. res, err := bulkService.Do(context.Background())
  383. if err != nil {
  384. return err
  385. }
  386. if len(res.Failed()) > 0 {
  387. return errors.New(res.Failed()[0].Error.Reason)
  388. }
  389. return nil
  390. }
  391. // 批量删除
  392. func (e *Elastic) DeleteBulk(index string, ids []string) {
  393. client := e.GetEsConn()
  394. defer e.DestoryEsConn(client)
  395. bulkService := client.Bulk().Index(index).Refresh("true")
  396. //bulkService.Type("bidding")
  397. for i := range ids {
  398. req := es.NewBulkDeleteRequest().Id(ids[i])
  399. bulkService.Add(req)
  400. }
  401. res, err := bulkService.Do(context.Background())
  402. if err != nil {
  403. fmt.Printf("DeleteBulk success is %v\n", len(res.Succeeded()))
  404. }
  405. }
  406. // InsertOrUpdate 插入或更新
  407. func (e *Elastic) InsertOrUpdate(index string, docs []map[string]interface{}) error {
  408. client := e.GetEsConn()
  409. defer e.DestoryEsConn(client)
  410. for _, item := range docs {
  411. // 获取唯一标识符
  412. id := item["id"].(string)
  413. if id == "" {
  414. id = item["_id"].(string)
  415. }
  416. // 根据id判断记录是否存在
  417. exists, err := client.Exists().
  418. Index(index).
  419. Id(id).
  420. Do(context.Background())
  421. if err != nil {
  422. return err
  423. }
  424. // 存在则更新,不存在则插入
  425. if exists {
  426. _, err := client.Update().
  427. Index(index).
  428. Id(id).
  429. Doc(item).
  430. Do(context.Background())
  431. if err != nil {
  432. return err
  433. }
  434. } else {
  435. _, err := client.Index().
  436. Index(index).
  437. Id(id).
  438. BodyJson(item).
  439. Do(context.Background())
  440. if err != nil {
  441. return err
  442. }
  443. }
  444. }
  445. return nil
  446. }
  447. //ExistsIndex 判断索引是否存在
  448. func (e *Elastic) ExistsIndex(index string) (exists bool, err error) {
  449. client := e.GetEsConn()
  450. defer e.DestoryEsConn(client)
  451. exists, err = client.IndexExists(index).Do(context.Background())
  452. return
  453. }
  454. //CreateIndex 创建索引
  455. func (e *Elastic) CreateIndex(index string, mapping string) (err error) {
  456. client := e.GetEsConn()
  457. defer e.DestoryEsConn(client)
  458. _, err = client.CreateIndex(index).BodyString(mapping).Do(context.Background())
  459. return
  460. }
  461. //DeleteIndex 删除索引
  462. func (e *Elastic) DeleteIndex(index string) (err error) {
  463. client := e.GetEsConn()
  464. defer e.DestoryEsConn(client)
  465. _, err = client.DeleteIndex(index).Do(context.Background())
  466. return
  467. }
  468. //RemoveAlias 移除别名
  469. func (e *Elastic) RemoveAlias(index, aliasName string) (err error) {
  470. client := e.GetEsConn()
  471. defer e.DestoryEsConn(client)
  472. _, err = client.Alias().Remove(index, aliasName).Do(context.Background())
  473. return
  474. }
  475. //SetAlias 添加别名
  476. func (e *Elastic) SetAlias(index, aliasName string) (err error) {
  477. client := e.GetEsConn()
  478. defer e.DestoryEsConn(client)
  479. _, err = client.Alias().Add(index, aliasName).Do(context.Background())
  480. return
  481. }
  482. //DeleteByID 根据ID 删除索引数据;id 或者索引名称不存在,都不会报错
  483. func (e *Elastic) DeleteByID(index, id string) error {
  484. client := e.GetEsConn()
  485. defer e.DestoryEsConn(client)
  486. _, err := client.Delete().Index(index).Id(id).Do(context.Background())
  487. if err != nil && es.IsNotFound(err) {
  488. return nil
  489. }
  490. return err
  491. }
  492. // UpdateDocument 更新指定ID的文档
  493. func (e *Elastic) UpdateDocument(indexName string, documentID string, updateData map[string]interface{}) error {
  494. client := e.GetEsConn()
  495. defer e.DestoryEsConn(client)
  496. updateResult, err := client.Update().
  497. Index(indexName).
  498. Id(documentID).
  499. Doc(updateData).
  500. Do(context.Background())
  501. if err != nil {
  502. return err
  503. }
  504. if updateResult.Result != "updated" {
  505. return fmt.Errorf("Document not updated: %v", updateResult.Result)
  506. }
  507. return nil
  508. }