eapi.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. package eapi
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "errors"
  7. "gadmin/config"
  8. "strings"
  9. "github.com/sirupsen/logrus"
  10. "github.com/spf13/cast"
  11. )
  12. // HasIndex 是否存在指定索引
  13. func HasIndex(ctx context.Context, index string) (has bool, err error) {
  14. client := config.GetElastic().Cat.Shards
  15. res, err := client(
  16. client.WithContext(ctx),
  17. )
  18. defer res.Body.Close()
  19. if err != nil {
  20. return
  21. }
  22. shards, err := String(res.Body)
  23. if err != nil {
  24. return
  25. }
  26. s1 := strings.Split(shards, "\n")
  27. for _, s := range s1 {
  28. s2 := strings.Split(s, " ")
  29. if len(s2) < 1 {
  30. continue
  31. }
  32. if s2[0] != "" && s2[0] == index {
  33. has = true
  34. return
  35. }
  36. }
  37. return
  38. }
  39. // CreateIndex 创建索引
  40. func CreateIndex(ctx context.Context, index string, dsl string) (err error) {
  41. if index == "" {
  42. err = errors.New("index names cannot be empty")
  43. return
  44. }
  45. hasIndex, err := HasIndex(ctx, index)
  46. if err != nil || hasIndex {
  47. return
  48. }
  49. body := &bytes.Buffer{}
  50. body.Write([]byte(dsl))
  51. client := config.GetElastic().Indices.Create
  52. // 创建一个新的索引
  53. res, err := client(
  54. index,
  55. client.WithContext(ctx),
  56. client.WithBody(body),
  57. )
  58. defer res.Body.Close()
  59. if err != nil {
  60. return
  61. }
  62. if res.IsError() {
  63. err = errors.New(res.String())
  64. return
  65. }
  66. return
  67. }
  68. // Bulk 批量操作
  69. // 批量操作对应ES的REST API是:
  70. // POST /<target>/_bulk
  71. // { "index" : { "_id" : "1" } }
  72. // { "field1" : "value1" }
  73. // { "delete" : { "_id" : "2" } }
  74. // { "create" : { "_id" : "3" } }
  75. // { "field1" : "value3" }
  76. // { "update" : {"_id" : "1" } }
  77. // { "doc" : {"field2" : "value2"} }
  78. // 对应index, create, update操作,
  79. // 提交的数据都是由两行组成,第一行是meta数据,描述操作信息
  80. // ,第二行是具体提交的数据,对于delete操作只有一行meta数据。 对照REST API
  81. func Bulk(ctx context.Context, index string, body *bytes.Buffer) (err error) {
  82. client := config.GetElastic().Bulk
  83. res, err := client(
  84. body,
  85. client.WithContext(ctx),
  86. client.WithIndex(index),
  87. )
  88. defer res.Body.Close()
  89. if err != nil {
  90. return
  91. }
  92. if res.IsError() {
  93. err = errors.New(res.String())
  94. return
  95. }
  96. logrus.Warnf(res.String())
  97. return
  98. }
  99. // Insert 插入数据
  100. func InsertToEs(ctx context.Context, index string, id, v any) (err error) {
  101. body := &bytes.Buffer{}
  102. if err = json.NewEncoder(body).Encode(v); err != nil {
  103. return
  104. }
  105. client := config.GetElastic().Create
  106. // 插入
  107. res, err := client(
  108. index,
  109. cast.ToString(id),
  110. body,
  111. client.WithContext(ctx),
  112. )
  113. defer res.Body.Close()
  114. if err != nil {
  115. return
  116. }
  117. if res.IsError() {
  118. err = errors.New(res.String())
  119. return
  120. }
  121. return
  122. }
  123. // Search 搜索数据
  124. func Search(ctx context.Context, index string, query map[string]interface{}) (sources []*Var, err error) {
  125. //query := map[string]interface{}{
  126. // "query": map[string]interface{}{
  127. // "match_phrase": map[string]interface{}{
  128. // "extra": `{"type":1}`,
  129. // },
  130. // },
  131. // "aggs": map[string]interface{}{ // 合查询语句的简写
  132. // "count_name": map[string]interface{}{ // 给聚合查询取个名字,
  133. // "value_count": map[string]interface{}{
  134. // "field": "name.keyword", //
  135. // },
  136. // },
  137. // },
  138. // //"from": 0,
  139. // //"size": 1,
  140. // //"sort": []map[string]interface{}{
  141. // // {"pubDate": []map[string]interface{}{
  142. // // {"order": "desc"},
  143. // // },
  144. // // },
  145. // //},
  146. //}
  147. marshal, err := json.Marshal(query)
  148. if err != nil {
  149. return
  150. }
  151. client := config.GetElastic().Search
  152. res, err := client(
  153. client.WithContext(ctx),
  154. client.WithIndex(index),
  155. client.WithBody(bytes.NewReader(marshal)),
  156. )
  157. defer res.Body.Close()
  158. if res.IsError() {
  159. err = errors.New(res.String())
  160. return
  161. }
  162. var search *SearchModel
  163. if err = Unmarshal(res.Body, &search); err != nil {
  164. return
  165. }
  166. if search == nil {
  167. return
  168. }
  169. for _, hit := range search.Hits.Hits {
  170. sources = append(sources, NewVar(hit.Source))
  171. }
  172. return
  173. }
  174. // Count 统计数据行
  175. func Count(ctx context.Context, index string, query map[string]interface{}) (total int64, err error) {
  176. marshal, err := json.Marshal(query)
  177. if err != nil {
  178. return
  179. }
  180. client := config.GetElastic().Count
  181. res, err := client(
  182. client.WithContext(ctx),
  183. client.WithIndex(index),
  184. client.WithBody(bytes.NewReader(marshal)),
  185. )
  186. defer res.Body.Close()
  187. if res.IsError() {
  188. err = errors.New(res.String())
  189. return
  190. }
  191. var count *CountModel
  192. err = Unmarshal(res.Body, &count)
  193. total = count.Count
  194. return
  195. }
  196. func DeleteByQuery(ctx context.Context, index []string, query map[string]interface{}) (err error) {
  197. marshal, err := json.Marshal(query)
  198. if err != nil {
  199. return
  200. }
  201. client := config.GetElastic().DeleteByQuery
  202. res, err := client(
  203. index,
  204. bytes.NewReader(marshal),
  205. client.WithContext(ctx),
  206. client.WithConflicts("proceed"),
  207. client.WithRefresh(true),
  208. )
  209. defer res.Body.Close()
  210. if res.IsError() {
  211. err = errors.New(res.String())
  212. return
  213. }
  214. //logrus.Warnf(res.String())
  215. return
  216. }
  217. // Cardinality 统计去重数据行
  218. func Cardinality(ctx context.Context, index string, query map[string]interface{}, field string) (total int64, err error) {
  219. query["_source"] = false
  220. query["size"] = 0
  221. query["aggs"] = M{
  222. "count": M{
  223. "cardinality": M{
  224. "field": field,
  225. },
  226. },
  227. }
  228. marshal, err := json.Marshal(query)
  229. if err != nil {
  230. return
  231. }
  232. client := config.GetElastic().Search
  233. res, err := client(
  234. client.WithContext(ctx),
  235. client.WithIndex(index),
  236. client.WithBody(bytes.NewReader(marshal)),
  237. )
  238. defer res.Body.Close()
  239. if res.IsError() {
  240. err = errors.New(res.String())
  241. return
  242. }
  243. var count *CardinalityModel
  244. if err = Unmarshal(res.Body, &count); err != nil {
  245. return
  246. }
  247. total = count.Aggregations.Count.Value
  248. return
  249. }
  250. // First 第一条数据
  251. func First(ctx context.Context, index string, field string) (val *Var, err error) {
  252. query := make(map[string]interface{})
  253. query["sort"] = M{
  254. field: "asc",
  255. }
  256. query["size"] = 1
  257. marshal, err := json.Marshal(query)
  258. if err != nil {
  259. return
  260. }
  261. client := config.GetElastic().Search
  262. res, err := client(
  263. client.WithContext(ctx),
  264. client.WithIndex(index),
  265. client.WithBody(bytes.NewReader(marshal)),
  266. )
  267. defer res.Body.Close()
  268. if res.IsError() {
  269. err = errors.New(res.String())
  270. return
  271. }
  272. var models *FirstModel
  273. if err = Unmarshal(res.Body, &models); err != nil {
  274. return
  275. }
  276. // 没有数据
  277. if len(models.Hits.Hits) == 0 {
  278. return
  279. }
  280. val = NewVar(models.Hits.Hits[0].Source)
  281. return
  282. }
  283. func FirstSan(ctx context.Context, index string, field string, v any) (err error) {
  284. val, err := First(ctx, index, field)
  285. if err != nil {
  286. return
  287. }
  288. return val.Scan(&v)
  289. }
  290. // Last 最后一条数据
  291. func Last(ctx context.Context, index string, query map[string]interface{}, field string) (val *Var, err error) {
  292. if query == nil {
  293. query = make(map[string]interface{})
  294. }
  295. query["sort"] = M{
  296. field: "desc",
  297. }
  298. query["size"] = 1
  299. marshal, err := json.Marshal(query)
  300. if err != nil {
  301. return
  302. }
  303. client := config.GetElastic().Search
  304. res, err := client(
  305. client.WithContext(ctx),
  306. client.WithIndex(index),
  307. client.WithBody(bytes.NewReader(marshal)),
  308. )
  309. defer res.Body.Close()
  310. if res.IsError() {
  311. err = errors.New(res.String())
  312. return
  313. }
  314. var models *FirstModel
  315. if err = Unmarshal(res.Body, &models); err != nil {
  316. return
  317. }
  318. // 没有数据
  319. if len(models.Hits.Hits) == 0 {
  320. return
  321. }
  322. val = NewVar(models.Hits.Hits[0].Source)
  323. return
  324. }
  325. func LastSan(ctx context.Context, index string, query map[string]interface{}, field string, v any) (err error) {
  326. val, err := Last(ctx, index, query, field)
  327. if err != nil {
  328. return
  329. }
  330. if val == nil {
  331. return
  332. }
  333. return val.Scan(&v)
  334. }
  335. // TopList 排行榜列表数据[index][user_id:score]
  336. func TopList(ctx context.Context, index string, query map[string]interface{}, field string, size int) (buckets []TopBucket, err error) {
  337. if query == nil {
  338. query = make(M)
  339. }
  340. query["_source"] = false
  341. query["aggs"] = M{
  342. "vals": M{
  343. "terms": M{
  344. "size": size,
  345. "field": field,
  346. },
  347. },
  348. }
  349. //logrus.Warnf("TopList index:%v\n where:%v\n", index, utility.DumpToJSON(query))
  350. marshal, err := json.Marshal(query)
  351. if err != nil {
  352. return
  353. }
  354. client := config.GetElastic().Search
  355. res, err := client(
  356. client.WithContext(ctx),
  357. client.WithIndex(index),
  358. client.WithBody(bytes.NewReader(marshal)),
  359. )
  360. defer res.Body.Close()
  361. if res.IsError() {
  362. err = errors.New(res.String())
  363. return
  364. }
  365. var models *TopListModel
  366. if err = Unmarshal(res.Body, &models); err != nil {
  367. return
  368. }
  369. // 没有数据
  370. if models == nil {
  371. return
  372. }
  373. buckets = models.Aggregations.Vals.Buckets
  374. return
  375. }
  376. // TopSumScore 聚合字段的排行榜
  377. func TopSumScore(ctx context.Context, index string, query map[string]interface{}, field, sumField string, size int) (buckets []TopSumScoreBucket, err error) {
  378. if query == nil {
  379. query = make(M)
  380. }
  381. query["size"] = 0
  382. query["aggs"] = M{
  383. "vals": M{
  384. "terms": M{
  385. "size": size,
  386. "field": field,
  387. "order": M{
  388. "sum_score": "desc",
  389. },
  390. },
  391. "aggs": M{
  392. "sum_score": M{
  393. "sum": M{
  394. "field": sumField,
  395. },
  396. },
  397. },
  398. },
  399. }
  400. marshal, err := json.Marshal(query)
  401. if err != nil {
  402. return
  403. }
  404. client := config.GetElastic().Search
  405. res, err := client(
  406. client.WithContext(ctx),
  407. client.WithIndex(index),
  408. client.WithBody(bytes.NewReader(marshal)),
  409. )
  410. if err != nil {
  411. return
  412. }
  413. defer res.Body.Close()
  414. if res.IsError() {
  415. err = errors.New(res.String())
  416. return
  417. }
  418. var models *TopSumScoreListModel
  419. if err = Unmarshal(res.Body, &models); err != nil {
  420. return
  421. }
  422. // 没有数据
  423. if models == nil {
  424. return
  425. }
  426. buckets = models.Aggregations.Vals.Buckets
  427. return
  428. }
  429. func ExistElastic() bool {
  430. return config.ExistElastic()
  431. }