es.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907
  1. package es
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "errors"
  7. "eta/eta_mini_ht_api/common/component/config"
  8. logger "eta/eta_mini_ht_api/common/component/log"
  9. "eta/eta_mini_ht_api/common/contants"
  10. "fmt"
  11. "github.com/elastic/go-elasticsearch/v7"
  12. "github.com/elastic/go-elasticsearch/v7/esapi"
  13. "io"
  14. "strconv"
  15. "strings"
  16. "sync"
  17. )
  18. type ESBase interface {
  19. GetId() string
  20. }
  21. var (
  22. esOnce sync.Once
  23. esClient *ESClient
  24. )
  25. type ESClient struct {
  26. esOp *elasticsearch.Client
  27. }
  28. type SearchType string
  29. const (
  30. MatchAll = "match_all"
  31. Match = "match"
  32. CountWithDocIds = "count_with_doc_ids"
  33. Range = "range"
  34. MatchAllByCondition = "match_all_by_condition"
  35. RangeByCondition = "range_by_condition"
  36. RangeByConditionWithDocIds = "range_by_condition_with_doc_ids"
  37. RangeByConditionWithDocIdsNoLimit = "range_by_condition_with_doc_ids_no_limit"
  38. RangeByConditionWithDocIdsNoLimitByScore = "range_by_condition_with_doc_ids_no_limit_by_score"
  39. RangeWithDocIds = "range_with_doc_ids"
  40. LimitByScore = "limit_by_score"
  41. HomeSearch = "home_search"
  42. )
  43. func GetInstance() *ESClient {
  44. esOnce.Do(func() {
  45. // 检查是否成功获取到RedisConfig实例,没有配置则不进行redis初始化
  46. if esConf, ok := config.GetConfig(contants.ES).(*config.ESConfig); ok {
  47. logger.Info("初始化es")
  48. // 这里可以添加初始化Redis的逻辑
  49. esClient = newEs(esConf)
  50. logger.Info("es地址:%v", esConf.GetUrl())
  51. }
  52. })
  53. return esClient
  54. }
  55. func (es *ESClient) es() *elasticsearch.Client {
  56. return es.esOp
  57. }
  58. func newEs(config *config.ESConfig) *ESClient {
  59. elasticsearch.NewDefaultClient()
  60. client, err := elasticsearch.NewClient(
  61. elasticsearch.Config{
  62. Addresses: []string{config.GetUrl()},
  63. // A list of Elasticsearch nodes to use.
  64. Username: config.GetUserName(),
  65. Password: config.GetPassword(), // Password for HTTP Basic Authentication.
  66. },
  67. )
  68. if err != nil {
  69. logger.Error("连接ES失败:%v", err)
  70. panic("启动es失败")
  71. }
  72. return &ESClient{esOp: client}
  73. }
  74. func init() {
  75. if GetInstance() == nil {
  76. panic("初始化es失败")
  77. }
  78. logger.Info("es初始化成功")
  79. }
  80. // BulkInsert 批量创建文档
  81. func (es *ESClient) BulkInsert(indexName string, docs []ESBase) (err error) {
  82. // 创建批量请求
  83. bulkBody := new(bytes.Buffer)
  84. for _, doc := range docs {
  85. enc := json.NewEncoder(bulkBody)
  86. if err = enc.Encode(map[string]interface{}{
  87. "index": map[string]interface{}{
  88. "_index": indexName,
  89. "_id": doc.GetId(),
  90. },
  91. }); err != nil {
  92. logger.Error("生成es批处理请求参数失败: %s", err)
  93. }
  94. if err = enc.Encode(doc); err != nil {
  95. logger.Error("生成es批处理文档失败: %s", err)
  96. }
  97. }
  98. bulkReq := esapi.BulkRequest{
  99. Body: bytes.NewReader(bulkBody.Bytes()),
  100. Refresh: "true",
  101. }
  102. res, err := bulkReq.Do(context.Background(), es.esOp)
  103. if err != nil {
  104. logger.Error("es批处理创建失败: %s", err)
  105. }
  106. defer res.Body.Close()
  107. if res.IsError() {
  108. var e map[string]interface{}
  109. if err = json.NewDecoder(res.Body).Decode(&e); err != nil {
  110. logger.Error("解析es应答失败: %v", err)
  111. } else {
  112. logger.Error("es请求失败: %s: %v\n", res.Status(), err)
  113. }
  114. }
  115. return
  116. }
  117. type ESResponse struct {
  118. Took int `json:"took"`
  119. Count int `json:"count"`
  120. TimedOut bool `json:"timedOut"`
  121. Hits Hits `json:"hits"`
  122. _Shards ShardsInfo `json:"_shards"`
  123. }
  124. type Hits struct {
  125. Total TotalHits `json:"total"`
  126. MaxScore float64 `json:"maxScore"`
  127. Hits []Hit `json:"hits"`
  128. }
  129. type TotalHits struct {
  130. Value int `json:"value"`
  131. Relation string `json:"relation"`
  132. }
  133. type Hit struct {
  134. Index string `json:"_index"`
  135. Type string `json:"_type"`
  136. ID string `json:"_id"`
  137. Score float64 `json:"_score"`
  138. Source json.RawMessage `json:"_source"`
  139. Highlight json.RawMessage `json:"highlight"`
  140. }
  141. type Doc struct {
  142. Index string `json:"_index"`
  143. Type string `json:"_type"`
  144. ID string `json:"_id"`
  145. Version float64 `json:"_version"`
  146. SeqNo float64 `json:"_seq_no"`
  147. PrimaryTerm float64 `json:"_primary_term"`
  148. Found bool `json:"found"`
  149. Source json.RawMessage `json:"_source"`
  150. }
  151. type ShardsInfo struct {
  152. Total int `json:"total"`
  153. Successful int `json:"successful"`
  154. Skipped int `json:"skipped"`
  155. Failed int `json:"failed"`
  156. }
  157. type ESQueryRequest struct {
  158. IndexName string
  159. From int
  160. Size int
  161. Key string
  162. Column string
  163. Condition string
  164. ConditionValue string
  165. Sorts []string
  166. Type SearchType
  167. RangeColumn string
  168. DocIds []string
  169. Max interface{}
  170. Min interface{}
  171. MinScore float64
  172. }
  173. func (req *ESQueryRequest) CreateESQueryRequest(index string, column string, key string, from int, size int, sorts []string, searchType SearchType) *ESQueryRequest {
  174. return &ESQueryRequest{
  175. IndexName: index,
  176. Type: searchType,
  177. From: from,
  178. Size: size,
  179. Key: key,
  180. Column: column,
  181. Sorts: sorts,
  182. }
  183. }
  184. func (req *ESQueryRequest) Limit(limit int) *ESQueryRequest {
  185. req.Size = limit
  186. return req
  187. }
  188. func (req *ESQueryRequest) WithScore(score float64) *ESQueryRequest {
  189. req.MinScore = score
  190. return req
  191. }
  192. func (req *ESQueryRequest) Range(from int64, to int64, column string) *ESQueryRequest {
  193. req.RangeColumn = column
  194. req.Max = to
  195. req.Min = from
  196. return req
  197. }
  198. func (req *ESQueryRequest) Before(max interface{}, column string) *ESQueryRequest {
  199. req.RangeColumn = column
  200. req.Max = max
  201. return req
  202. }
  203. func (req *ESQueryRequest) ByCondition(column string, value string) *ESQueryRequest {
  204. req.Condition = column
  205. req.ConditionValue = value
  206. return req
  207. }
  208. func (req *ESQueryRequest) WithDocs(docIds []string) *ESQueryRequest {
  209. req.DocIds = docIds
  210. return req
  211. }
  212. func (req *ESQueryRequest) parseJsonQuery() (queryMap map[string]interface{}) {
  213. switch req.Type {
  214. case MatchAll:
  215. queryMap = map[string]interface{}{
  216. "query": map[string]interface{}{
  217. "match": map[string]interface{}{
  218. req.Column: req.Key,
  219. },
  220. },
  221. }
  222. return
  223. case MatchAllByCondition:
  224. queryMap = map[string]interface{}{
  225. "query": map[string]interface{}{
  226. "bool": map[string]interface{}{
  227. "must": []map[string]interface{}{
  228. {
  229. "match": map[string]interface{}{
  230. req.Column: req.Key,
  231. },
  232. },
  233. {
  234. "term": map[string]interface{}{
  235. req.Condition: req.ConditionValue,
  236. },
  237. },
  238. },
  239. },
  240. },
  241. }
  242. return
  243. case Match:
  244. queryMap = map[string]interface{}{
  245. "query": map[string]interface{}{
  246. "match": map[string]interface{}{
  247. req.Column: req.Key,
  248. },
  249. },
  250. "highlight": map[string]interface{}{
  251. "fields": map[string]interface{}{
  252. req.Column: map[string]interface{}{},
  253. },
  254. "pre_tags": []string{"<span style='color:#0078E8'>"},
  255. "post_tags": []string{"</span>"},
  256. },
  257. }
  258. return
  259. case CountWithDocIds:
  260. queryMap = map[string]interface{}{
  261. "query": map[string]interface{}{
  262. "bool": map[string]interface{}{
  263. "must": []map[string]interface{}{
  264. {
  265. "match": map[string]interface{}{
  266. req.Column: req.Key,
  267. },
  268. },
  269. },
  270. "filter": map[string]interface{}{
  271. "terms": map[string]interface{}{
  272. "_id": req.DocIds,
  273. },
  274. },
  275. },
  276. },
  277. }
  278. return
  279. case Range:
  280. queryMap = map[string]interface{}{
  281. "query": map[string]interface{}{
  282. "match": map[string]interface{}{
  283. req.Column: req.Key,
  284. },
  285. },
  286. "highlight": map[string]interface{}{
  287. "fields": map[string]interface{}{
  288. req.Column: map[string]interface{}{},
  289. },
  290. "pre_tags": []string{"<span style='color:#0078E8'>"},
  291. "post_tags": []string{"</span>"},
  292. },
  293. "post_filter": map[string]interface{}{
  294. "range": map[string]interface{}{
  295. req.RangeColumn: map[string]interface{}{
  296. "gte": req.Min,
  297. "lte": req.Max,
  298. },
  299. },
  300. },
  301. }
  302. return
  303. case RangeWithDocIds:
  304. queryMap = map[string]interface{}{
  305. "query": map[string]interface{}{
  306. "match": map[string]interface{}{
  307. req.Column: req.Key,
  308. },
  309. },
  310. "highlight": map[string]interface{}{
  311. "fields": map[string]interface{}{
  312. req.Column: map[string]interface{}{},
  313. },
  314. "pre_tags": []string{"<span style='color:#0078E8'>"},
  315. "post_tags": []string{"</span>"},
  316. },
  317. "post_filter": map[string]interface{}{
  318. "bool": map[string]interface{}{
  319. "must": []map[string]interface{}{
  320. {
  321. "range": map[string]interface{}{
  322. req.RangeColumn: map[string]interface{}{
  323. "gte": req.Min,
  324. "lte": req.Max,
  325. },
  326. },
  327. },
  328. {
  329. "terms": map[string]interface{}{
  330. "_id": req.DocIds,
  331. },
  332. },
  333. },
  334. },
  335. },
  336. }
  337. return
  338. case RangeByCondition:
  339. queryMap = map[string]interface{}{
  340. "query": map[string]interface{}{
  341. "match": map[string]interface{}{
  342. req.Column: req.Key,
  343. },
  344. },
  345. "highlight": map[string]interface{}{
  346. "fields": map[string]interface{}{
  347. req.Column: map[string]interface{}{},
  348. },
  349. "pre_tags": []string{"<span style='color:#0078E8'>"},
  350. "post_tags": []string{"</span>"},
  351. },
  352. "post_filter": map[string]interface{}{
  353. "bool": map[string]interface{}{
  354. "must": []map[string]interface{}{
  355. {
  356. "range": map[string]interface{}{
  357. req.RangeColumn: map[string]interface{}{
  358. "gte": req.Min,
  359. "lte": req.Max,
  360. },
  361. },
  362. },
  363. {
  364. "term": map[string]interface{}{
  365. req.Condition: req.ConditionValue,
  366. },
  367. },
  368. },
  369. },
  370. },
  371. }
  372. return
  373. case RangeByConditionWithDocIds:
  374. queryMap = map[string]interface{}{
  375. "query": map[string]interface{}{
  376. "match": map[string]interface{}{
  377. req.Column: req.Key,
  378. },
  379. },
  380. "highlight": map[string]interface{}{
  381. "fields": map[string]interface{}{
  382. req.Column: map[string]interface{}{},
  383. },
  384. "pre_tags": []string{"<span style='color:#0078E8'>"},
  385. "post_tags": []string{"</span>"},
  386. },
  387. "post_filter": map[string]interface{}{
  388. "bool": map[string]interface{}{
  389. "must": []map[string]interface{}{
  390. {
  391. "range": map[string]interface{}{
  392. req.RangeColumn: map[string]interface{}{
  393. "gte": req.Min,
  394. "lte": req.Max,
  395. },
  396. },
  397. },
  398. {
  399. "term": map[string]interface{}{
  400. req.Condition: req.ConditionValue,
  401. },
  402. },
  403. {
  404. "terms": map[string]interface{}{
  405. "_id": req.DocIds,
  406. },
  407. },
  408. },
  409. },
  410. },
  411. }
  412. return
  413. case RangeByConditionWithDocIdsNoLimit:
  414. queryMap = map[string]interface{}{
  415. "query": map[string]interface{}{
  416. "match": map[string]interface{}{
  417. req.Column: req.Key,
  418. },
  419. },
  420. "highlight": map[string]interface{}{
  421. "fields": map[string]interface{}{
  422. req.Column: map[string]interface{}{},
  423. },
  424. "pre_tags": []string{"<span style='color:#0078E8'>"},
  425. "post_tags": []string{"</span>"},
  426. },
  427. "post_filter": map[string]interface{}{
  428. "bool": map[string]interface{}{
  429. "must": []map[string]interface{}{
  430. {
  431. "terms": map[string]interface{}{
  432. "_id": req.DocIds,
  433. },
  434. },
  435. },
  436. },
  437. },
  438. }
  439. return
  440. case RangeByConditionWithDocIdsNoLimitByScore:
  441. queryMap = map[string]interface{}{
  442. "query": map[string]interface{}{
  443. "match": map[string]interface{}{
  444. req.Column: req.Key,
  445. },
  446. },
  447. "highlight": map[string]interface{}{
  448. "fields": map[string]interface{}{
  449. req.Column: map[string]interface{}{},
  450. },
  451. "pre_tags": []string{"<span style='color:#0078E8'>"},
  452. "post_tags": []string{"</span>"},
  453. },
  454. "post_filter": map[string]interface{}{
  455. "bool": map[string]interface{}{
  456. "must": []map[string]interface{}{
  457. {
  458. "terms": map[string]interface{}{
  459. "_id": req.DocIds,
  460. },
  461. },
  462. },
  463. },
  464. },
  465. "min_score": req.MinScore,
  466. }
  467. return
  468. case LimitByScore:
  469. queryMap = map[string]interface{}{
  470. "query": map[string]interface{}{
  471. "match": map[string]interface{}{
  472. req.Column: req.Key,
  473. },
  474. },
  475. "highlight": map[string]interface{}{
  476. "fields": map[string]interface{}{
  477. req.Column: map[string]interface{}{},
  478. },
  479. "pre_tags": []string{"<span style='color:#0078E8'>"},
  480. "post_tags": []string{"</span>"},
  481. },
  482. "post_filter": map[string]interface{}{
  483. "bool": map[string]interface{}{
  484. "must": []map[string]interface{}{
  485. {
  486. "terms": map[string]interface{}{
  487. "_id": req.DocIds,
  488. },
  489. },
  490. },
  491. },
  492. },
  493. "min_score": req.MinScore,
  494. }
  495. return
  496. case HomeSearch:
  497. queryMap = map[string]interface{}{
  498. "query": map[string]interface{}{
  499. "bool": map[string]interface{}{
  500. "should": []map[string]interface{}{
  501. {
  502. "bool": map[string]interface{}{
  503. "must": []map[string]interface{}{
  504. {
  505. "match": map[string]interface{}{
  506. "title": req.Key,
  507. },
  508. },
  509. {
  510. "term": map[string]interface{}{
  511. "status": "PUBLISH",
  512. },
  513. },
  514. {
  515. "range": map[string]interface{}{
  516. "publishedTime": map[string]interface{}{
  517. "lte": req.Max,
  518. },
  519. },
  520. },
  521. },
  522. },
  523. },
  524. {
  525. "bool": map[string]interface{}{
  526. "must": []map[string]interface{}{
  527. {
  528. "match": map[string]interface{}{
  529. "mediaName": req.Key,
  530. },
  531. },
  532. {
  533. "range": map[string]interface{}{
  534. req.RangeColumn: map[string]interface{}{
  535. "lte": req.Max,
  536. },
  537. },
  538. },
  539. },
  540. },
  541. },
  542. },
  543. },
  544. },
  545. "highlight": map[string]interface{}{
  546. "fields": map[string]interface{}{
  547. "title": map[string]interface{}{},
  548. "mediaName": map[string]interface{}{},
  549. },
  550. "pre_tags": []string{"<span style='color:#0078E8'>"},
  551. "post_tags": []string{"</span>"},
  552. },
  553. }
  554. return
  555. default:
  556. queryMap = map[string]interface{}{}
  557. return
  558. }
  559. }
  560. // /*
  561. // *
  562. //
  563. // 搜索
  564. //
  565. // indexName 访问索引名
  566. // query 搜索条件
  567. // from 开始搜索位置
  568. // size 搜索条数
  569. // sort 排序
  570. // */
  571. func (es *ESClient) Count(params *ESQueryRequest) (response ESResponse, err error) {
  572. queryMap := params.parseJsonQuery()
  573. jsonQuery, _ := json.Marshal(queryMap)
  574. logger.Info("查询语句: %s", string(jsonQuery))
  575. request := esapi.CountRequest{
  576. Index: []string{params.IndexName},
  577. Body: strings.NewReader(string(jsonQuery)),
  578. }
  579. res, err := request.Do(context.Background(), esClient.esOp)
  580. defer res.Body.Close()
  581. if err != nil {
  582. logger.Error("es查询失败: %s", err)
  583. }
  584. if res.IsError() {
  585. var e map[string]interface{}
  586. if err = json.NewDecoder(res.Body).Decode(&e); err != nil {
  587. logger.Error("解析es应答失败: %v", err)
  588. } else {
  589. logger.Error("es请求失败: %s: %v\n", res.Status(), e)
  590. }
  591. }
  592. body, err := io.ReadAll(res.Body)
  593. if err != nil {
  594. logger.Error("获取es应答失败: %v", err)
  595. }
  596. return parseESResponse(body)
  597. }
  598. func (es *ESClient) Search(params *ESQueryRequest) (response ESResponse, err error) {
  599. queryMap := params.parseJsonQuery()
  600. jsonQuery, _ := json.Marshal(queryMap)
  601. logger.Info("查询语句: %s", string(jsonQuery))
  602. indexes := strings.Split(params.IndexName, ",")
  603. request := esapi.SearchRequest{
  604. Index: indexes,
  605. Body: strings.NewReader(string(jsonQuery)),
  606. From: &params.From,
  607. Size: &params.Size,
  608. Sort: params.Sorts,
  609. }
  610. res, err := request.Do(context.Background(), esClient.esOp)
  611. defer res.Body.Close()
  612. if err != nil {
  613. logger.Error("es查询失败: %s", err)
  614. }
  615. if res.IsError() {
  616. var e map[string]interface{}
  617. if err = json.NewDecoder(res.Body).Decode(&e); err != nil {
  618. logger.Error("解析es应答失败: %v", err)
  619. } else {
  620. logger.Error("es请求失败: %s: %v\n", res.Status(), e)
  621. }
  622. }
  623. body, err := io.ReadAll(res.Body)
  624. if err != nil {
  625. logger.Error("获取es应答失败: %v", err)
  626. }
  627. return parseESResponse(body)
  628. }
  629. func parseESResponse(body []byte) (ESResponse, error) {
  630. var response ESResponse
  631. if err := json.Unmarshal(body, &response); err != nil {
  632. return ESResponse{}, err
  633. }
  634. for _, hit := range response.Hits.Hits {
  635. var source map[string]interface{}
  636. if err := json.Unmarshal(hit.Source, &source); err != nil {
  637. return ESResponse{}, err
  638. }
  639. }
  640. return response, nil
  641. }
  642. func (es *ESClient) GetSource(hits Hits) []Hit {
  643. return hits.Hits
  644. }
  645. func (es *ESClient) GetCount(hits Hits) []Hit {
  646. return hits.Hits
  647. }
  648. // /*
  649. // *
  650. // 添加es
  651. // indexName 索引名
  652. // id es的id
  653. // body es的值
  654. // */
  655. func (es *ESClient) Update(indexName string, id int, doc interface{}) bool {
  656. jsonUpdate := map[string]interface{}{
  657. "doc": doc,
  658. }
  659. jsonDoc, _ := json.Marshal(jsonUpdate)
  660. logger.Info("查询语句: %s", string(jsonDoc))
  661. req := esapi.UpdateRequest{
  662. Index: indexName,
  663. DocumentID: strconv.Itoa(id),
  664. Body: strings.NewReader(string(jsonDoc)),
  665. Refresh: "true",
  666. }
  667. res, err := req.Do(context.Background(), es.es())
  668. defer res.Body.Close()
  669. if err != nil {
  670. logger.Error("es查询失败: %s", err)
  671. }
  672. if res.IsError() {
  673. var e map[string]interface{}
  674. if err = json.NewDecoder(res.Body).Decode(&e); err != nil {
  675. logger.Error("解析es应答失败: %v", err)
  676. } else {
  677. logger.Error("es请求失败: %s: %v\n", res.Status(), e)
  678. }
  679. }
  680. body, err := io.ReadAll(res.Body)
  681. if err != nil {
  682. logger.Error("获取es应答失败: %v", err)
  683. }
  684. fmt.Printf("%s\n", string(body))
  685. return true
  686. }
  687. func (es *ESClient) InsertOrUpdate(indexName string, id int, doc interface{}) (success bool) {
  688. if exist, existErr := es.Exist(indexName, id); existErr == nil && exist {
  689. return es.Update(indexName, id, doc)
  690. } else {
  691. return es.CreateDocument(indexName, id, doc)
  692. }
  693. }
  694. // Delete *
  695. // 删除
  696. // indexName 索引名
  697. // id es的id
  698. // */
  699. func (es *ESClient) Delete(indexName string, query interface{}) bool {
  700. jsonQuery, _ := json.Marshal(query)
  701. refresh := new(bool)
  702. *refresh = true
  703. logger.Info("查询语句: %s", string(jsonQuery))
  704. req := esapi.DeleteByQueryRequest{
  705. Index: []string{indexName},
  706. Body: strings.NewReader(string(jsonQuery)),
  707. Refresh: refresh,
  708. }
  709. res, err := req.Do(context.Background(), es.es())
  710. defer res.Body.Close()
  711. if err != nil {
  712. logger.Error("es查询失败: %s", err)
  713. }
  714. if res.IsError() {
  715. var e map[string]interface{}
  716. if err = json.NewDecoder(res.Body).Decode(&e); err != nil {
  717. logger.Error("解析es应答失败: %v", err)
  718. } else {
  719. logger.Error("es请求失败: %s: %v\n", res.Status(), e)
  720. }
  721. }
  722. body, err := io.ReadAll(res.Body)
  723. if err != nil {
  724. logger.Error("获取es应答失败: %v", err)
  725. }
  726. fmt.Printf("%s\n", string(body))
  727. return true
  728. }
  729. func (es *ESClient) Exist(indexName string, docId int) (exist bool, err error) {
  730. getRequest := esapi.GetRequest{
  731. Index: indexName,
  732. DocumentID: strconv.Itoa(docId),
  733. }
  734. // 执行请求
  735. res, err := getRequest.Do(context.Background(), es.es())
  736. if err != nil {
  737. logger.Error("es获取文档是否存在失败: %v", err)
  738. return
  739. }
  740. defer res.Body.Close()
  741. // 检查文档是否存在
  742. if res.IsError() {
  743. // 如果文档不存在,通常返回 404 Not Found
  744. if res.StatusCode == 404 {
  745. logger.Info("文档不存在.")
  746. err = errors.New("ES文档不存在")
  747. return
  748. } else {
  749. // 其他错误
  750. var e map[string]interface{}
  751. if err = json.NewDecoder(res.Body).Decode(&e); err != nil {
  752. logger.Error("解析es应答失败: %v", err)
  753. return
  754. } else {
  755. // Print the response status and error information.
  756. logger.Error("[%s] %s: %s\n", res.Status(), e["error"].(map[string]interface{})["type"], e["error"].(map[string]interface{})["原因"])
  757. err = errors.New("获取ES记录失败")
  758. return
  759. }
  760. }
  761. } else {
  762. // 如果文档存在
  763. logger.Info("doc存在")
  764. return true, nil
  765. }
  766. }
  767. func (es *ESClient) Get(indexName string, docId int) (doc Doc, err error) {
  768. getRequest := esapi.GetRequest{
  769. Index: indexName,
  770. DocumentID: strconv.Itoa(docId),
  771. }
  772. // 执行请求
  773. res, err := getRequest.Do(context.Background(), es.es())
  774. if err != nil {
  775. logger.Error("es获取文档是否存在失败: %v", err)
  776. return
  777. }
  778. defer res.Body.Close()
  779. // 检查文档是否存在
  780. if res.IsError() {
  781. // 如果文档不存在,通常返回 404 Not Found
  782. if res.StatusCode == 404 {
  783. logger.Info("文档不存在.")
  784. err = errors.New("ES文档不存在")
  785. return
  786. } else {
  787. // 其他错误
  788. var e map[string]interface{}
  789. if err = json.NewDecoder(res.Body).Decode(&e); err != nil {
  790. logger.Error("解析es应答失败: %v", err)
  791. return
  792. } else {
  793. // Print the response status and error information.
  794. logger.Error("[%s] %s: %s\n", res.Status(), e["error"].(map[string]interface{})["type"], e["error"].(map[string]interface{})["原因"])
  795. err = errors.New("获取ES记录失败")
  796. return
  797. }
  798. }
  799. } else {
  800. // 如果文档存在
  801. body, readErr := io.ReadAll(res.Body)
  802. if readErr != nil {
  803. logger.Error("获取es应答失败: %v", err)
  804. err = readErr
  805. return
  806. }
  807. err = json.Unmarshal(body, &doc)
  808. if err != nil {
  809. logger.Error("反序列化es应答失败: %v", err)
  810. return
  811. }
  812. return
  813. }
  814. }
  815. //
  816. //func CreateIndex(indexName string) error {
  817. // resp, err := esClient.es().Indices.
  818. // Create(indexName).
  819. // Do(context.Background())
  820. // if err != nil {
  821. // logger.Error("创建ES索引失败:%v", err)
  822. // return err
  823. // }
  824. // fmt.Printf("index:%#v\n", resp.Index)
  825. // return nil
  826. //}
  827. // DeleteIndex 删除索引
  828. //
  829. // func DeleteIndex(indexName string) error {
  830. // _, err := esClient.es().Indices. // 表明是对索引的操作,而Index则表示是要操作具体索引下的文档
  831. // Delete(indexName).
  832. // Do(context.Background())
  833. // if err != nil {
  834. // fmt.Printf("delete index failed,err:%v\n", err)
  835. // return err
  836. // }
  837. // fmt.Printf("delete index successed,indexName:%s", indexName)
  838. // return nil
  839. // }
  840. //
  841. // CreateDocument 创建文档
  842. func (es *ESClient) CreateDocument(indexName string, id int, doc interface{}) (success bool) {
  843. jsonDoc, _ := json.Marshal(doc)
  844. logger.Info("查询语句: %s", string(jsonDoc))
  845. // 添加文档
  846. indexRequest := esapi.IndexRequest{
  847. Index: indexName,
  848. DocumentID: strconv.Itoa(id),
  849. Body: strings.NewReader(string(jsonDoc)),
  850. Refresh: "true",
  851. }
  852. // 执行请求
  853. res, err := indexRequest.Do(context.Background(), es.es())
  854. if err != nil {
  855. logger.Error("ES创建文档失败: %s", err)
  856. return false
  857. }
  858. defer res.Body.Close()
  859. // 检查文档是否成功创建
  860. if res.IsError() {
  861. var e map[string]interface{}
  862. if err := json.NewDecoder(res.Body).Decode(&e); err != nil {
  863. logger.Error("解析ES应答失败: %s", err)
  864. } else {
  865. // Print the response status and error information.
  866. logger.Error("[%s] %s: %s\n", res.Status(), e["error"].(map[string]interface{})["类型"], e["错误"].(map[string]interface{})["原因"])
  867. }
  868. return false
  869. } else {
  870. // 如果文档成功创建
  871. logger.Info("创建文档成功")
  872. return true
  873. }
  874. }