elasticSim.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. package elastic
  2. import (
  3. util "app.yhyue.com/data_processing/common_utils"
  4. "context"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. es "github.com/olivere/elastic/v7"
  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, query string) *[]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).Source(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. delete(v, "_id")
  165. req = req.Add(es.NewBulkIndexRequest().Index(index).Id(id).Doc(v))
  166. }
  167. _, err := req.Do(context.Background())
  168. if err != nil {
  169. log.Println("批量保存到ES出错", err.Error())
  170. }
  171. }
  172. }
  173. //根据id删除索引对象
  174. func (e *Elastic) DelById(index, id string) bool {
  175. client := e.GetEsConn()
  176. defer e.DestoryEsConn(client)
  177. b := false
  178. if client != nil {
  179. var err error
  180. _, err = client.Delete().Index(index).Id(id).Do(context.Background())
  181. if err != nil {
  182. log.Println("更新检索出错:", err.Error())
  183. } else {
  184. b = true
  185. }
  186. }
  187. return b
  188. }
  189. func (e *Elastic) GetNoLimit(index, query string) *[]map[string]interface{} {
  190. client := e.GetEsConn()
  191. defer e.DestoryEsConn(client)
  192. var res []map[string]interface{}
  193. if client != nil {
  194. defer func() {
  195. if r := recover(); r != nil {
  196. log.Println("[E]", r)
  197. for skip := 1; ; skip++ {
  198. _, file, line, ok := runtime.Caller(skip)
  199. if !ok {
  200. break
  201. }
  202. go log.Printf("%v,%v\n", file, line)
  203. }
  204. }
  205. }()
  206. searchResult, err := client.Search().Index(index).Source(query).Do(context.Background())
  207. if err != nil {
  208. log.Println("从ES查询出错", err.Error())
  209. return nil
  210. }
  211. if searchResult.Hits != nil {
  212. resNum := len(searchResult.Hits.Hits)
  213. res = make([]map[string]interface{}, resNum)
  214. for i, hit := range searchResult.Hits.Hits {
  215. json.Unmarshal(hit.Source, &res[i])
  216. }
  217. }
  218. }
  219. return &res
  220. }
  221. //func (e *Elastic) GetByIdField(index, itype, id, fields string) *map[string]interface{} {
  222. // client := e.GetEsConn()
  223. // defer e.DestoryEsConn(client)
  224. // if client != nil {
  225. // defer func() {
  226. // if r := recover(); r != nil {
  227. // log.Println("[E]", r)
  228. // for skip := 1; ; skip++ {
  229. // _, file, line, ok := runtime.Caller(skip)
  230. // if !ok {
  231. // break
  232. // }
  233. // go log.Printf("%v,%v\n", file, line)
  234. // }
  235. // }
  236. // }()
  237. // query := `{"query":{"term":{"_id":"` + id + `"}}`
  238. // if len(fields) > 0 {
  239. // query = query + `,"_source":[` + fields + `]`
  240. // }
  241. // query = query + "}"
  242. // searchResult, err := client.Search().Index(index).Type(itype).Source(query).Do()
  243. // if err != nil {
  244. // log.Println("从ES查询出错", err.Error())
  245. // return nil
  246. // }
  247. // var res map[string]interface{}
  248. // if searchResult.Hits != nil {
  249. // resNum := len(searchResult.Hits.Hits)
  250. // if resNum == 1 {
  251. // res = make(map[string]interface{})
  252. // for _, hit := range searchResult.Hits.Hits {
  253. // json.Unmarshal(*hit.Source., &res)
  254. // }
  255. // return &res
  256. // }
  257. // }
  258. // }
  259. // return nil
  260. //}
  261. func (e *Elastic) Count(index, itype string, query interface{}) int64 {
  262. client := e.GetEsConn()
  263. defer e.DestoryEsConn(client)
  264. if client != nil {
  265. defer func() {
  266. if r := recover(); r != nil {
  267. log.Println("[E]", r)
  268. for skip := 1; ; skip++ {
  269. _, file, line, ok := runtime.Caller(skip)
  270. if !ok {
  271. break
  272. }
  273. go log.Printf("%v,%v\n", file, line)
  274. }
  275. }
  276. }()
  277. var qq es.Query
  278. if qi, ok2 := query.(es.Query); ok2 {
  279. qq = qi
  280. }
  281. n, err := client.Count(index).Query(qq).Do(context.Background())
  282. if err != nil {
  283. log.Println("统计出错", err.Error())
  284. }
  285. return n
  286. }
  287. return 0
  288. }
  289. //更新一个字段
  290. //func (e *Elastic) BulkUpdateArr(index, itype string, update []map[string]string) {
  291. // client := e.GetEsConn()
  292. // defer e.DestoryEsConn(client)
  293. // if client != nil {
  294. // defer func() {
  295. // if r := recover(); r != nil {
  296. // log.Println("[E]", r)
  297. // for skip := 1; ; skip++ {
  298. // _, file, line, ok := runtime.Caller(skip)
  299. // if !ok {
  300. // break
  301. // }
  302. // go log.Printf("%v,%v\n", file, line)
  303. // }
  304. // }
  305. // }()
  306. // for _, data := range update {
  307. // id := data["id"]
  308. // updateStr := data["updateStr"]
  309. // if id != "" && updateStr != "" {
  310. // _, err := client.Update().Index(index).Type(itype).Id(id).Script(updateStr).ScriptLang("groovy").Do()
  311. // if err != nil {
  312. // log.Println("更新检索出错:", err.Error())
  313. // }
  314. // } else {
  315. // log.Println("数据错误")
  316. // }
  317. // }
  318. // }
  319. //}
  320. //更新多个字段
  321. //func (e *Elastic) BulkUpdateMultipleFields(index, itype string, arrs [][]map[string]interface{}) {
  322. // client := e.GetEsConn()
  323. // defer e.DestoryEsConn(client)
  324. // if client != nil {
  325. // defer func() {
  326. // if r := recover(); r != nil {
  327. // log.Println("[E]", r)
  328. // for skip := 1; ; skip++ {
  329. // _, file, line, ok := runtime.Caller(skip)
  330. // if !ok {
  331. // break
  332. // }
  333. // go log.Printf("%v,%v\n", file, line)
  334. // }
  335. // }
  336. // }()
  337. // for _, arr := range arrs {
  338. // id := arr[0]["id"].(string)
  339. // update := arr[1]["update"].([]string)
  340. // for _, str := range update {
  341. // _, err := client.Update().Index(index).Type(itype).Id(id).Script(str).ScriptLang("groovy").Do()
  342. // if err != nil {
  343. // log.Println("更新检索出错:", err.Error())
  344. // }
  345. // }
  346. // }
  347. // }
  348. //}
  349. // UpdateBulk 批量修改文档
  350. func (e *Elastic) UpdateBulk(index, itype string, docs ...[]map[string]interface{}) {
  351. client := e.GetEsConn()
  352. defer e.DestoryEsConn(client)
  353. bulkService := client.Bulk().Index(index).Refresh("true")
  354. // bulkService.Type(itype)
  355. for _, d := range docs {
  356. id := d[0]["_id"].(string)
  357. doc := es.NewBulkUpdateRequest().Id(id).Doc(d[1])
  358. bulkService.Add(doc)
  359. }
  360. _, err := bulkService.Do(context.Background())
  361. if err != nil {
  362. fmt.Printf("UpdateBulk all success err is %v\n", err)
  363. }
  364. //if len(res.Failed()) > 0 {
  365. // fmt.Printf("UpdateBulk all success failed is %v\n", (res.Items[0]))
  366. //}
  367. }
  368. // UpsertBulk 批量修改文档(不存在则插入)
  369. func (e *Elastic) UpsertBulk(ctx context.Context, index string, ids []string, docs []interface{}) error {
  370. client := e.GetEsConn()
  371. defer e.DestoryEsConn(client)
  372. bulkService := client.Bulk().Index(index).Refresh("true")
  373. // bulkService.Type("bidding")
  374. for i := range ids {
  375. doc := es.NewBulkUpdateRequest().Id(ids[i]).Doc(docs[i]).Upsert(docs[i])
  376. bulkService.Add(doc)
  377. }
  378. res, err := bulkService.Do(context.Background())
  379. if err != nil {
  380. return err
  381. }
  382. if len(res.Failed()) > 0 {
  383. return errors.New(res.Failed()[0].Error.Reason)
  384. }
  385. return nil
  386. }
  387. // 批量删除
  388. func (e *Elastic) DeleteBulk(index string, ids []string) {
  389. client := e.GetEsConn()
  390. defer e.DestoryEsConn(client)
  391. bulkService := client.Bulk().Index(index).Refresh("true")
  392. bulkService.Type("bidding")
  393. for i := range ids {
  394. req := es.NewBulkDeleteRequest().Id(ids[i])
  395. bulkService.Add(req)
  396. }
  397. res, err := bulkService.Do(context.Background())
  398. if err != nil {
  399. fmt.Printf("DeleteBulk success is %v\n", len(res.Succeeded()))
  400. }
  401. }