elasticSim.go 10 KB

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