es.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  1. package es
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "eta/eta_mini_ht_api/common/component/config"
  7. logger "eta/eta_mini_ht_api/common/component/log"
  8. "eta/eta_mini_ht_api/common/contants"
  9. "fmt"
  10. "github.com/elastic/go-elasticsearch/v7"
  11. "github.com/elastic/go-elasticsearch/v7/esapi"
  12. "io"
  13. "strconv"
  14. "strings"
  15. "sync"
  16. )
  17. type ESBase interface {
  18. GetId() string
  19. }
  20. var (
  21. esOnce sync.Once
  22. esClient *ESClient
  23. )
  24. type ESClient struct {
  25. esOp *elasticsearch.Client
  26. }
  27. type SearchType string
  28. const (
  29. MatchAll = "match_all"
  30. Match = "match"
  31. CountWithDocIds = "count_with_doc_ids"
  32. Range = "range"
  33. MatchAllByCondition = "match_all_by_condition"
  34. RangeByCondition = "range_by_condition"
  35. RangeByConditionWithDocIds = "range_by_condition_with_doc_ids"
  36. RangeWithDocIds = "range_with_doc_ids"
  37. )
  38. func GetInstance() *ESClient {
  39. esOnce.Do(func() {
  40. // 检查是否成功获取到RedisConfig实例,没有配置则不进行redis初始化
  41. if esConf, ok := config.GetConfig(contants.ES).(*config.ESConfig); ok {
  42. logger.Info("初始化es")
  43. // 这里可以添加初始化Redis的逻辑
  44. esClient = newEs(esConf)
  45. }
  46. })
  47. return esClient
  48. }
  49. func (es *ESClient) es() *elasticsearch.Client {
  50. return es.esOp
  51. }
  52. func newEs(config *config.ESConfig) *ESClient {
  53. elasticsearch.NewDefaultClient()
  54. client, err := elasticsearch.NewClient(
  55. elasticsearch.Config{
  56. Addresses: []string{config.GetUrl()},
  57. // A list of Elasticsearch nodes to use.
  58. Username: config.GetUserName(),
  59. Password: config.GetPassword(), // Password for HTTP Basic Authentication.
  60. },
  61. )
  62. if err != nil {
  63. logger.Error("连接ES失败:%v", err)
  64. panic("启动es失败")
  65. }
  66. return &ESClient{esOp: client}
  67. }
  68. func init() {
  69. if GetInstance() == nil {
  70. panic("初始化es失败")
  71. }
  72. logger.Info("es初始化成功")
  73. }
  74. // BulkInsert 批量创建文档
  75. func (es *ESClient) BulkInsert(indexName string, docs []ESBase) (err error) {
  76. // 创建批量请求
  77. bulkBody := new(bytes.Buffer)
  78. for _, doc := range docs {
  79. enc := json.NewEncoder(bulkBody)
  80. if err = enc.Encode(map[string]interface{}{
  81. "index": map[string]interface{}{
  82. "_index": indexName,
  83. "_id": doc.GetId(),
  84. },
  85. }); err != nil {
  86. logger.Error("生成es批处理请求参数失败: %s", err)
  87. }
  88. if err = enc.Encode(doc); err != nil {
  89. logger.Error("生成es批处理文档失败: %s", err)
  90. }
  91. }
  92. bulkReq := esapi.BulkRequest{
  93. Body: bytes.NewReader(bulkBody.Bytes()),
  94. Refresh: "true",
  95. }
  96. res, err := bulkReq.Do(context.Background(), es.esOp)
  97. if err != nil {
  98. logger.Error("es批处理创建失败: %s", err)
  99. }
  100. defer res.Body.Close()
  101. if res.IsError() {
  102. var e map[string]interface{}
  103. if err = json.NewDecoder(res.Body).Decode(&e); err != nil {
  104. logger.Error("解析es应答失败: %v", err)
  105. } else {
  106. logger.Error("es请求失败: %s: %v\n", res.Status(), err)
  107. }
  108. }
  109. return
  110. }
  111. type ESResponse struct {
  112. Took int `json:"took"`
  113. Count int `json:"count"`
  114. TimedOut bool `json:"timedOut"`
  115. Hits Hits `json:"hits"`
  116. _Shards ShardsInfo `json:"_shards"`
  117. }
  118. type Hits struct {
  119. Total TotalHits `json:"total"`
  120. MaxScore float64 `json:"maxScore"`
  121. Hits []Hit `json:"hits"`
  122. }
  123. type TotalHits struct {
  124. Value int `json:"value"`
  125. Relation string `json:"relation"`
  126. }
  127. type Hit struct {
  128. Index string `json:"_index"`
  129. Type string `json:"_type"`
  130. ID string `json:"_id"`
  131. Score float64 `json:"_score"`
  132. Source json.RawMessage `json:"_source"`
  133. Highlight json.RawMessage `json:"highlight"`
  134. }
  135. type ShardsInfo struct {
  136. Total int `json:"total"`
  137. Successful int `json:"successful"`
  138. Skipped int `json:"skipped"`
  139. Failed int `json:"failed"`
  140. }
  141. type ESQueryRequest struct {
  142. IndexName string
  143. From int
  144. Size int
  145. Key string
  146. Column string
  147. Condition string
  148. ConditionValue string
  149. Sorts []string
  150. Type SearchType
  151. RangeColumn string
  152. DocIds []string
  153. Max interface{}
  154. Min interface{}
  155. }
  156. func (req *ESQueryRequest) CreateESQueryRequest(index string, column string, key string, from int, size int, sorts []string, searchType SearchType) *ESQueryRequest {
  157. return &ESQueryRequest{
  158. IndexName: index,
  159. Type: searchType,
  160. From: from,
  161. Size: size,
  162. Key: key,
  163. Column: column,
  164. Sorts: sorts,
  165. }
  166. }
  167. func (req *ESQueryRequest) Range(from int64, to int64, column string) *ESQueryRequest {
  168. req.RangeColumn = column
  169. req.Max = to
  170. req.Min = from
  171. return req
  172. }
  173. func (req *ESQueryRequest) ByCondition(column string, value string) *ESQueryRequest {
  174. req.Condition = column
  175. req.ConditionValue = value
  176. return req
  177. }
  178. func (req *ESQueryRequest) WithDocs(docIds []string) *ESQueryRequest {
  179. req.DocIds = docIds
  180. return req
  181. }
  182. func (req *ESQueryRequest) parseJsonQuery() (queryMap map[string]interface{}) {
  183. switch req.Type {
  184. case MatchAll:
  185. queryMap = map[string]interface{}{
  186. "query": map[string]interface{}{
  187. "match": map[string]interface{}{
  188. req.Column: req.Key,
  189. },
  190. },
  191. }
  192. return
  193. case MatchAllByCondition:
  194. queryMap = map[string]interface{}{
  195. "query": map[string]interface{}{
  196. "bool": map[string]interface{}{
  197. "must": []map[string]interface{}{
  198. {
  199. "match": map[string]interface{}{
  200. req.Column: req.Key,
  201. },
  202. },
  203. {
  204. "term": map[string]interface{}{
  205. req.Condition: req.ConditionValue,
  206. },
  207. },
  208. },
  209. },
  210. },
  211. }
  212. return
  213. case Match:
  214. queryMap = map[string]interface{}{
  215. "query": map[string]interface{}{
  216. "match": map[string]interface{}{
  217. req.Column: req.Key,
  218. },
  219. },
  220. "highlight": map[string]interface{}{
  221. "fields": map[string]interface{}{
  222. req.Column: map[string]interface{}{},
  223. },
  224. "pre_tags": []string{"<span style='color:#0078E8'>"},
  225. "post_tags": []string{"</span>"},
  226. },
  227. }
  228. return
  229. case CountWithDocIds:
  230. queryMap = map[string]interface{}{
  231. "query": map[string]interface{}{
  232. "bool": map[string]interface{}{
  233. "must": []map[string]interface{}{
  234. {
  235. "match": map[string]interface{}{
  236. req.Column: req.Key,
  237. },
  238. },
  239. },
  240. "filter": map[string]interface{}{
  241. "terms": map[string]interface{}{
  242. "_id": req.DocIds,
  243. },
  244. },
  245. },
  246. },
  247. }
  248. return
  249. case Range:
  250. queryMap = map[string]interface{}{
  251. "query": map[string]interface{}{
  252. "match": map[string]interface{}{
  253. req.Column: req.Key,
  254. },
  255. },
  256. "highlight": map[string]interface{}{
  257. "fields": map[string]interface{}{
  258. req.Column: map[string]interface{}{},
  259. },
  260. "pre_tags": []string{"<span style='color:#0078E8'>"},
  261. "post_tags": []string{"</span>"},
  262. },
  263. "post_filter": map[string]interface{}{
  264. "range": map[string]interface{}{
  265. req.RangeColumn: map[string]interface{}{
  266. "gte": req.Min,
  267. "lte": req.Max,
  268. },
  269. },
  270. },
  271. }
  272. return
  273. case RangeWithDocIds:
  274. queryMap = map[string]interface{}{
  275. "query": map[string]interface{}{
  276. "match": map[string]interface{}{
  277. req.Column: req.Key,
  278. },
  279. },
  280. "highlight": map[string]interface{}{
  281. "fields": map[string]interface{}{
  282. req.Column: map[string]interface{}{},
  283. },
  284. "pre_tags": []string{"<span style='color:#0078E8'>"},
  285. "post_tags": []string{"</span>"},
  286. },
  287. "post_filter": map[string]interface{}{
  288. "bool": map[string]interface{}{
  289. "must": []map[string]interface{}{
  290. {
  291. "range": map[string]interface{}{
  292. req.RangeColumn: map[string]interface{}{
  293. "gte": req.Min,
  294. "lte": req.Max,
  295. },
  296. },
  297. },
  298. {
  299. "terms": map[string]interface{}{
  300. "_id": req.DocIds,
  301. },
  302. },
  303. },
  304. },
  305. },
  306. }
  307. return
  308. case RangeByCondition:
  309. queryMap = map[string]interface{}{
  310. "query": map[string]interface{}{
  311. "match": map[string]interface{}{
  312. req.Column: req.Key,
  313. },
  314. },
  315. "highlight": map[string]interface{}{
  316. "fields": map[string]interface{}{
  317. req.Column: map[string]interface{}{},
  318. },
  319. "pre_tags": []string{"<span style='color:#0078E8'>"},
  320. "post_tags": []string{"</span>"},
  321. },
  322. "post_filter": map[string]interface{}{
  323. "bool": map[string]interface{}{
  324. "must": []map[string]interface{}{
  325. {
  326. "range": map[string]interface{}{
  327. req.RangeColumn: map[string]interface{}{
  328. "gte": req.Min,
  329. "lte": req.Max,
  330. },
  331. },
  332. },
  333. {
  334. "term": map[string]interface{}{
  335. req.Condition: req.ConditionValue,
  336. },
  337. },
  338. },
  339. },
  340. },
  341. }
  342. return
  343. case RangeByConditionWithDocIds:
  344. queryMap = map[string]interface{}{
  345. "query": map[string]interface{}{
  346. "match": map[string]interface{}{
  347. req.Column: req.Key,
  348. },
  349. },
  350. "highlight": map[string]interface{}{
  351. "fields": map[string]interface{}{
  352. req.Column: map[string]interface{}{},
  353. },
  354. "pre_tags": []string{"<span style='color:#0078E8'>"},
  355. "post_tags": []string{"</span>"},
  356. },
  357. "post_filter": map[string]interface{}{
  358. "bool": map[string]interface{}{
  359. "must": []map[string]interface{}{
  360. {
  361. "range": map[string]interface{}{
  362. req.RangeColumn: map[string]interface{}{
  363. "gte": req.Min,
  364. "lte": req.Max,
  365. },
  366. },
  367. },
  368. {
  369. "term": map[string]interface{}{
  370. req.Condition: req.ConditionValue,
  371. },
  372. },
  373. {
  374. "terms": map[string]interface{}{
  375. "_id": req.DocIds,
  376. },
  377. },
  378. },
  379. },
  380. },
  381. }
  382. return
  383. default:
  384. queryMap = map[string]interface{}{}
  385. return
  386. }
  387. }
  388. // /*
  389. // *
  390. //
  391. // 搜索
  392. //
  393. // indexName 访问索引名
  394. // query 搜索条件
  395. // from 开始搜索位置
  396. // size 搜索条数
  397. // sort 排序
  398. // */
  399. func (es *ESClient) Count(params *ESQueryRequest) (response ESResponse, err error) {
  400. queryMap := params.parseJsonQuery()
  401. jsonQuery, _ := json.Marshal(queryMap)
  402. logger.Info("查询语句: %s", string(jsonQuery))
  403. request := esapi.CountRequest{
  404. Index: []string{params.IndexName},
  405. Body: strings.NewReader(string(jsonQuery)),
  406. }
  407. res, err := request.Do(context.Background(), esClient.esOp)
  408. defer res.Body.Close()
  409. if err != nil {
  410. logger.Error("es查询失败: %s", err)
  411. }
  412. if res.IsError() {
  413. var e map[string]interface{}
  414. if err = json.NewDecoder(res.Body).Decode(&e); err != nil {
  415. logger.Error("解析es应答失败: %v", err)
  416. } else {
  417. logger.Error("es请求失败: %s: %v\n", res.Status(), e)
  418. }
  419. }
  420. body, err := io.ReadAll(res.Body)
  421. if err != nil {
  422. logger.Error("获取es应答失败: %v", err)
  423. }
  424. return parseESResponse(body)
  425. }
  426. func (es *ESClient) Search(params *ESQueryRequest) (response ESResponse, err error) {
  427. queryMap := params.parseJsonQuery()
  428. jsonQuery, _ := json.Marshal(queryMap)
  429. logger.Info("查询语句: %s", string(jsonQuery))
  430. request := esapi.SearchRequest{
  431. Index: []string{params.IndexName},
  432. Body: strings.NewReader(string(jsonQuery)),
  433. From: &params.From,
  434. Size: &params.Size,
  435. Sort: params.Sorts,
  436. }
  437. res, err := request.Do(context.Background(), esClient.esOp)
  438. defer res.Body.Close()
  439. if err != nil {
  440. logger.Error("es查询失败: %s", err)
  441. }
  442. if res.IsError() {
  443. var e map[string]interface{}
  444. if err = json.NewDecoder(res.Body).Decode(&e); err != nil {
  445. logger.Error("解析es应答失败: %v", err)
  446. } else {
  447. logger.Error("es请求失败: %s: %v\n", res.Status(), e)
  448. }
  449. }
  450. body, err := io.ReadAll(res.Body)
  451. if err != nil {
  452. logger.Error("获取es应答失败: %v", err)
  453. }
  454. return parseESResponse(body)
  455. }
  456. func parseESResponse(body []byte) (ESResponse, error) {
  457. var response ESResponse
  458. if err := json.Unmarshal(body, &response); err != nil {
  459. return ESResponse{}, err
  460. }
  461. for _, hit := range response.Hits.Hits {
  462. var source map[string]interface{}
  463. if err := json.Unmarshal(hit.Source, &source); err != nil {
  464. return ESResponse{}, err
  465. }
  466. }
  467. return response, nil
  468. }
  469. func (es *ESClient) GetSource(hits Hits) []Hit {
  470. return hits.Hits
  471. }
  472. func (es *ESClient) GetCount(hits Hits) []Hit {
  473. return hits.Hits
  474. }
  475. // /*
  476. // *
  477. // 添加es
  478. // indexName 索引名
  479. // id es的id
  480. // body es的值
  481. // */
  482. func (es *ESClient) Update(indexName string, id int, doc interface{}) bool {
  483. jsonUpdate := map[string]interface{}{
  484. "doc": doc,
  485. }
  486. jsonDoc, _ := json.Marshal(jsonUpdate)
  487. logger.Info("查询语句: %s", string(jsonDoc))
  488. req := esapi.UpdateRequest{
  489. Index: indexName,
  490. DocumentID: strconv.Itoa(id),
  491. Body: strings.NewReader(string(jsonDoc)),
  492. Refresh: "true",
  493. }
  494. res, err := req.Do(context.Background(), es.es())
  495. defer res.Body.Close()
  496. if err != nil {
  497. logger.Error("es查询失败: %s", err)
  498. }
  499. if res.IsError() {
  500. var e map[string]interface{}
  501. if err = json.NewDecoder(res.Body).Decode(&e); err != nil {
  502. logger.Error("解析es应答失败: %v", err)
  503. } else {
  504. logger.Error("es请求失败: %s: %v\n", res.Status(), e)
  505. }
  506. }
  507. body, err := io.ReadAll(res.Body)
  508. if err != nil {
  509. logger.Error("获取es应答失败: %v", err)
  510. }
  511. fmt.Printf("%s\n", string(body))
  512. return true
  513. }
  514. // Delete *
  515. // 删除
  516. // indexName 索引名
  517. // id es的id
  518. // */
  519. func (es *ESClient) Delete(indexName string, id int) bool {
  520. req := esapi.DeleteRequest{
  521. Index: indexName,
  522. DocumentID: strconv.Itoa(id),
  523. Refresh: "true",
  524. }
  525. res, err := req.Do(context.Background(), es.es())
  526. defer res.Body.Close()
  527. if err != nil {
  528. logger.Error("es查询失败: %s", err)
  529. }
  530. if res.IsError() {
  531. var e map[string]interface{}
  532. if err = json.NewDecoder(res.Body).Decode(&e); err != nil {
  533. logger.Error("解析es应答失败: %v", err)
  534. } else {
  535. logger.Error("es请求失败: %s: %v\n", res.Status(), e)
  536. }
  537. }
  538. body, err := io.ReadAll(res.Body)
  539. if err != nil {
  540. logger.Error("获取es应答失败: %v", err)
  541. }
  542. fmt.Printf("%s\n", string(body))
  543. return true
  544. }
  545. func (es *ESClient) Exist(indexName string, docId int) (exist bool, err error) {
  546. getRequest := esapi.GetRequest{
  547. Index: indexName,
  548. DocumentID: strconv.Itoa(docId),
  549. }
  550. // 执行请求
  551. res, err := getRequest.Do(context.Background(), es.es())
  552. if err != nil {
  553. logger.Error("es获取文档是否存在失败: %v", err)
  554. }
  555. defer res.Body.Close()
  556. // 检查文档是否存在
  557. if res.IsError() {
  558. // 如果文档不存在,通常返回 404 Not Found
  559. if res.StatusCode == 404 {
  560. logger.Info("文档不存在.")
  561. return false, nil
  562. } else {
  563. // 其他错误
  564. var e map[string]interface{}
  565. if err = json.NewDecoder(res.Body).Decode(&e); err != nil {
  566. logger.Error("解析es应答失败: %v", err)
  567. return false, err
  568. } else {
  569. // Print the response status and error information.
  570. logger.Error("[%s] %s: %s\n", res.Status(), e["error"].(map[string]interface{})["type"], e["error"].(map[string]interface{})["原因"])
  571. return false, nil
  572. }
  573. }
  574. } else {
  575. // 如果文档存在
  576. logger.Info("doc存在")
  577. return true, nil
  578. }
  579. }
  580. //
  581. //func CreateIndex(indexName string) error {
  582. // resp, err := esClient.es().Indices.
  583. // Create(indexName).
  584. // Do(context.Background())
  585. // if err != nil {
  586. // logger.Error("创建ES索引失败:%v", err)
  587. // return err
  588. // }
  589. // fmt.Printf("index:%#v\n", resp.Index)
  590. // return nil
  591. //}
  592. // DeleteIndex 删除索引
  593. //
  594. // func DeleteIndex(indexName string) error {
  595. // _, err := esClient.es().Indices. // 表明是对索引的操作,而Index则表示是要操作具体索引下的文档
  596. // Delete(indexName).
  597. // Do(context.Background())
  598. // if err != nil {
  599. // fmt.Printf("delete index failed,err:%v\n", err)
  600. // return err
  601. // }
  602. // fmt.Printf("delete index successed,indexName:%s", indexName)
  603. // return nil
  604. // }
  605. //
  606. // CreateDocument 创建文档
  607. func (es *ESClient) CreateDocument(indexName string, id int, doc interface{}) (success bool) {
  608. jsonDoc, _ := json.Marshal(doc)
  609. logger.Info("查询语句: %s", string(jsonDoc))
  610. // 添加文档
  611. indexRequest := esapi.IndexRequest{
  612. Index: indexName,
  613. DocumentID: strconv.Itoa(id),
  614. Body: strings.NewReader(string(jsonDoc)),
  615. Refresh: "true",
  616. }
  617. // 执行请求
  618. res, err := indexRequest.Do(context.Background(), es.es())
  619. if err != nil {
  620. logger.Error("ES创建文档失败: %s", err)
  621. return false
  622. }
  623. defer res.Body.Close()
  624. // 检查文档是否成功创建
  625. if res.IsError() {
  626. var e map[string]interface{}
  627. if err := json.NewDecoder(res.Body).Decode(&e); err != nil {
  628. logger.Error("解析ES应答失败: %s", err)
  629. } else {
  630. // Print the response status and error information.
  631. logger.Error("[%s] %s: %s\n", res.Status(), e["error"].(map[string]interface{})["类型"], e["错误"].(map[string]interface{})["原因"])
  632. }
  633. return false
  634. } else {
  635. // 如果文档成功创建
  636. logger.Info("创建文档成功")
  637. return true
  638. }
  639. }