elasticSim.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. package elastic
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. es "github.com/olivere/elastic/v7"
  7. "log"
  8. "runtime"
  9. "strings"
  10. "sync"
  11. "time"
  12. )
  13. type Elastic struct {
  14. S_esurl string
  15. I_size int
  16. Addrs []string
  17. Pool chan *es.Client
  18. lastTime int64
  19. lastTimeLock sync.Mutex
  20. ntimeout int
  21. }
  22. func (e *Elastic) InitElasticSize() {
  23. e.Pool = make(chan *es.Client, e.I_size)
  24. for _, s := range strings.Split(e.S_esurl, ",") {
  25. e.Addrs = append(e.Addrs, s)
  26. }
  27. for i := 0; i < e.I_size; i++ {
  28. client, _ := es.NewClient(es.SetURL(e.Addrs...), es.SetMaxRetries(2), es.SetSniff(false))
  29. e.Pool <- client
  30. }
  31. }
  32. //关闭连接
  33. func (e *Elastic) DestoryEsConn(client *es.Client) {
  34. select {
  35. case e.Pool <- client:
  36. break
  37. case <-time.After(time.Second * 1):
  38. if client != nil {
  39. client.Stop()
  40. }
  41. client = nil
  42. }
  43. }
  44. func (e *Elastic) GetEsConn() *es.Client {
  45. select {
  46. case c := <-e.Pool:
  47. if c == nil || !c.IsRunning() {
  48. log.Println("new esclient.", len(e.Pool))
  49. client, err := es.NewClient(es.SetURL(e.Addrs...),
  50. es.SetMaxRetries(2), es.SetSniff(false))
  51. if err == nil && client.IsRunning() {
  52. return client
  53. }
  54. }
  55. return c
  56. case <-time.After(time.Second * 4):
  57. //超时
  58. e.ntimeout++
  59. e.lastTimeLock.Lock()
  60. defer e.lastTimeLock.Unlock()
  61. //12秒后允许创建链接
  62. c := time.Now().Unix() - e.lastTime
  63. if c > 12 {
  64. e.lastTime = time.Now().Unix()
  65. log.Println("add client..", len(e.Pool))
  66. c, _ := es.NewClient(es.SetURL(e.Addrs...), es.SetMaxRetries(2), es.SetSniff(false))
  67. go func() {
  68. for i := 0; i < 2; i++ {
  69. client, _ := es.NewClient(es.SetURL(e.Addrs...), es.SetMaxRetries(2), es.SetSniff(false))
  70. e.Pool <- client
  71. }
  72. }()
  73. return c
  74. }
  75. return nil
  76. }
  77. }
  78. //
  79. //func (e *Elastic) Get(index, itype, query string) *[]map[string]interface{} {
  80. // client := e.GetEsConn()
  81. // defer func() {
  82. // go e.DestoryEsConn(client)
  83. // }()
  84. // var res []map[string]interface{}
  85. // if client != nil {
  86. // defer func() {
  87. // if r := recover(); r != nil {
  88. // log.Println("[E]", r)
  89. // for skip := 1; ; skip++ {
  90. // _, file, line, ok := runtime.Caller(skip)
  91. // if !ok {
  92. // break
  93. // }
  94. // go log.Printf("%v,%v\n", file, line)
  95. // }
  96. // }
  97. // }()
  98. // searchResult, err := client.Search().Index(index).Source(query).Do(context.Background())
  99. // if err != nil {
  100. // log.Println("从ES查询出错", err.Error())
  101. // return nil
  102. // }
  103. // if searchResult.Hits != nil {
  104. // resNum := len(searchResult.Hits.Hits)
  105. // if resNum < 5000 {
  106. // res = make([]map[string]interface{}, resNum)
  107. // for i, hit := range searchResult.Hits.Hits {
  108. // parseErr := json.Unmarshal(*hit.Source, &res[i])
  109. // if parseErr == nil && hit.Highlight != nil && res[i] != nil {
  110. // res[i]["highlight"] = map[string][]string(hit.Highlight)
  111. // }
  112. // }
  113. // } else {
  114. // log.Println("查询结果太多,查询到:", resNum, "条")
  115. // }
  116. // }
  117. // }
  118. // return &res
  119. //}
  120. //关闭elastic
  121. func (e *Elastic) Close() {
  122. for i := 0; i < e.I_size; i++ {
  123. cli := <-e.Pool
  124. cli.Stop()
  125. cli = nil
  126. }
  127. e.Pool = nil
  128. e = nil
  129. }
  130. //获取连接
  131. //func (e *Elastic) GetEsConn() (c *es.Client) {
  132. // defer util.Catch()
  133. // select {
  134. // case c = <-e.Pool:
  135. // if c == nil || !c.IsRunning() {
  136. // client, err := es.NewClient(es.SetURL(addrs...),
  137. // es.SetMaxRetries(2), es.SetSniff(false))
  138. // if err == nil && client.IsRunning() {
  139. // return client
  140. // }
  141. // return nil
  142. // }
  143. // return
  144. // case <-time.After(time.Second * 7):
  145. // //超时
  146. // ntimeout++
  147. // log.Println("timeout times:", ntimeout)
  148. // return nil
  149. // }
  150. //}
  151. func (e *Elastic) BulkSave(index, itype string, obj *[]map[string]interface{}, isDelBefore bool) {
  152. client := e.GetEsConn()
  153. defer e.DestoryEsConn(client)
  154. if client != nil {
  155. req := client.Bulk()
  156. for _, v := range *obj {
  157. if isDelBefore {
  158. req = req.Add(es.NewBulkDeleteRequest().Index(index).Type(itype).Id(fmt.Sprintf("%v", v["id"])))
  159. }
  160. req = req.Add(es.NewBulkIndexRequest().Index(index).Type(itype).Doc(v))
  161. }
  162. _, err := req.Do(context.Background())
  163. if err != nil {
  164. log.Println("批量保存到ES出错", err.Error())
  165. }
  166. }
  167. }
  168. //根据id删除索引对象
  169. func (e *Elastic) DelById(index, itype, id string) bool {
  170. client := e.GetEsConn()
  171. defer e.DestoryEsConn(client)
  172. b := false
  173. if client != nil {
  174. var err error
  175. _, err = client.Delete().Index(index).Type(itype).Id(id).Do(context.Background())
  176. if err != nil {
  177. log.Println("更新检索出错:", err.Error())
  178. } else {
  179. b = true
  180. }
  181. }
  182. return b
  183. }
  184. //func (e *Elastic) GetNoLimit(index, itype, query string) *[]map[string]interface{} {
  185. // //log.Println("query -- ", query)
  186. // client := e.GetEsConn()
  187. // defer e.DestoryEsConn(client)
  188. // var res []map[string]interface{}
  189. // if client != nil {
  190. // defer func() {
  191. // if r := recover(); r != nil {
  192. // log.Println("[E]", r)
  193. // for skip := 1; ; skip++ {
  194. // _, file, line, ok := runtime.Caller(skip)
  195. // if !ok {
  196. // break
  197. // }
  198. // go log.Printf("%v,%v\n", file, line)
  199. // }
  200. // }
  201. // }()
  202. // searchResult, err := client.Search().Index(index).Source(query).Do(context.Background())
  203. // if err != nil {
  204. // log.Println("从ES查询出错", err.Error())
  205. // return nil
  206. // }
  207. //
  208. // if searchResult.Hits != nil {
  209. // resNum := len(searchResult.Hits.Hits)
  210. // res = make([]map[string]interface{}, resNum)
  211. // for i, hit := range searchResult.Hits.Hits {
  212. // json.Unmarshal(*hit.Source, &res[i])
  213. // }
  214. // }
  215. // }
  216. // return &res
  217. //}
  218. //func (e *Elastic) GetByIdField(index, itype, id, fields string) *map[string]interface{} {
  219. // client := e.GetEsConn()
  220. // defer e.DestoryEsConn(client)
  221. // if client != nil {
  222. // defer func() {
  223. // if r := recover(); r != nil {
  224. // log.Println("[E]", r)
  225. // for skip := 1; ; skip++ {
  226. // _, file, line, ok := runtime.Caller(skip)
  227. // if !ok {
  228. // break
  229. // }
  230. // go log.Printf("%v,%v\n", file, line)
  231. // }
  232. // }
  233. // }()
  234. // query := `{"query":{"term":{"_id":"` + id + `"}}`
  235. // if len(fields) > 0 {
  236. // query = query + `,"_source":[` + fields + `]`
  237. // }
  238. // query = query + "}"
  239. // searchResult, err := client.Search().Index(index).Type(itype).Source(query).Do()
  240. // if err != nil {
  241. // log.Println("从ES查询出错", err.Error())
  242. // return nil
  243. // }
  244. // var res map[string]interface{}
  245. // if searchResult.Hits != nil {
  246. // resNum := len(searchResult.Hits.Hits)
  247. // if resNum == 1 {
  248. // res = make(map[string]interface{})
  249. // for _, hit := range searchResult.Hits.Hits {
  250. // json.Unmarshal(*hit.Source., &res)
  251. // }
  252. // return &res
  253. // }
  254. // }
  255. // }
  256. // return nil
  257. //}
  258. func (e *Elastic) Count(index, itype string, query interface{}) int64 {
  259. client := e.GetEsConn()
  260. defer e.DestoryEsConn(client)
  261. if client != nil {
  262. defer func() {
  263. if r := recover(); r != nil {
  264. log.Println("[E]", r)
  265. for skip := 1; ; skip++ {
  266. _, file, line, ok := runtime.Caller(skip)
  267. if !ok {
  268. break
  269. }
  270. go log.Printf("%v,%v\n", file, line)
  271. }
  272. }
  273. }()
  274. var qq es.Query
  275. if qi, ok2 := query.(es.Query); ok2 {
  276. qq = qi
  277. }
  278. n, err := client.Count(index).Query(qq).Do(context.Background())
  279. if err != nil {
  280. log.Println("统计出错", err.Error())
  281. }
  282. return n
  283. }
  284. return 0
  285. }
  286. //更新一个字段
  287. //func (e *Elastic) BulkUpdateArr(index, itype string, update []map[string]string) {
  288. // client := e.GetEsConn()
  289. // defer e.DestoryEsConn(client)
  290. // if client != nil {
  291. // defer func() {
  292. // if r := recover(); r != nil {
  293. // log.Println("[E]", r)
  294. // for skip := 1; ; skip++ {
  295. // _, file, line, ok := runtime.Caller(skip)
  296. // if !ok {
  297. // break
  298. // }
  299. // go log.Printf("%v,%v\n", file, line)
  300. // }
  301. // }
  302. // }()
  303. // for _, data := range update {
  304. // id := data["id"]
  305. // updateStr := data["updateStr"]
  306. // if id != "" && updateStr != "" {
  307. // _, err := client.Update().Index(index).Type(itype).Id(id).Script(updateStr).ScriptLang("groovy").Do()
  308. // if err != nil {
  309. // log.Println("更新检索出错:", err.Error())
  310. // }
  311. // } else {
  312. // log.Println("数据错误")
  313. // }
  314. // }
  315. // }
  316. //}
  317. //更新多个字段
  318. //func (e *Elastic) BulkUpdateMultipleFields(index, itype string, arrs [][]map[string]interface{}) {
  319. // client := e.GetEsConn()
  320. // defer e.DestoryEsConn(client)
  321. // if client != nil {
  322. // defer func() {
  323. // if r := recover(); r != nil {
  324. // log.Println("[E]", r)
  325. // for skip := 1; ; skip++ {
  326. // _, file, line, ok := runtime.Caller(skip)
  327. // if !ok {
  328. // break
  329. // }
  330. // go log.Printf("%v,%v\n", file, line)
  331. // }
  332. // }
  333. // }()
  334. // for _, arr := range arrs {
  335. // id := arr[0]["id"].(string)
  336. // update := arr[1]["update"].([]string)
  337. // for _, str := range update {
  338. // _, err := client.Update().Index(index).Type(itype).Id(id).Script(str).ScriptLang("groovy").Do()
  339. // if err != nil {
  340. // log.Println("更新检索出错:", err.Error())
  341. // }
  342. // }
  343. // }
  344. // }
  345. //}
  346. // UpdateBulk 批量修改文档
  347. func (e *Elastic) UpdateBulk(index, itype string, docs ...[]map[string]interface{}) {
  348. client := e.GetEsConn()
  349. defer e.DestoryEsConn(client)
  350. bulkService := client.Bulk().Index(index).Refresh("true")
  351. bulkService.Type(itype)
  352. for _, d := range docs {
  353. id := d[0]["_id"].(string)
  354. doc := es.NewBulkUpdateRequest().Id(id).Doc(d[1])
  355. bulkService.Add(doc)
  356. }
  357. _, err := bulkService.Do(context.Background())
  358. if err != nil {
  359. fmt.Printf("UpdateBulk all success err is %v\n", err)
  360. }
  361. //if len(res.Failed()) > 0 {
  362. // fmt.Printf("UpdateBulk all success failed is %v\n", (res.Items[0]))
  363. //}
  364. }
  365. // UpsertBulk 批量修改文档(不存在则插入)
  366. func (e *Elastic) UpsertBulk(ctx context.Context, index string, ids []string, docs []interface{}) error {
  367. client := e.GetEsConn()
  368. defer e.DestoryEsConn(client)
  369. bulkService := client.Bulk().Index(index).Refresh("true")
  370. bulkService.Type("bidding")
  371. for i := range ids {
  372. doc := es.NewBulkUpdateRequest().Id(ids[i]).Doc(docs[i]).Upsert(docs[i])
  373. bulkService.Add(doc)
  374. }
  375. res, err := bulkService.Do(context.Background())
  376. if err != nil {
  377. return err
  378. }
  379. if len(res.Failed()) > 0 {
  380. return errors.New(res.Failed()[0].Error.Reason)
  381. }
  382. return nil
  383. }
  384. // 批量删除
  385. func (e *Elastic) DeleteBulk(index string, ids []string) {
  386. client := e.GetEsConn()
  387. defer e.DestoryEsConn(client)
  388. bulkService := client.Bulk().Index(index).Refresh("true")
  389. bulkService.Type("bidding")
  390. for i := range ids {
  391. req := es.NewBulkDeleteRequest().Id(ids[i])
  392. bulkService.Add(req)
  393. }
  394. res, err := bulkService.Do(context.Background())
  395. if err != nil {
  396. fmt.Printf("DeleteBulk success is %v\n", len(res.Succeeded()))
  397. }
  398. }