elasticSim.go 10 KB

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