ESOne.groovy 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import com.dySweetFishPlugin.elasticsearch.ESClient
  2. import com.yinjie.heating.common.api.ESHitInfoExecutor
  3. import com.yinjie.heating.common.api.QueryBuilderExecutor
  4. import com.sweetfish.convert.json.JsonConvert
  5. import org.elasticsearch.action.search.SearchResponse
  6. import org.elasticsearch.index.query.QueryBuilder
  7. import org.elasticsearch.search.SearchHit
  8. /**
  9. * Created by jlutt on 2022-04-20
  10. *
  11. * @author jlutt
  12. */
  13. class ESOne<T> {
  14. private ESClient esClient
  15. private JsonConvert jsonConvert
  16. private Class<T> clazz
  17. private QueryBuilderExecutor qbe
  18. private String index
  19. private ESHitInfoExecutor<T> de
  20. static <T> ESOne<T> getESOneInfo() {
  21. return new ESOne<>()
  22. }
  23. ESOne<T> esClient(ESClient value) {
  24. this.esClient = value
  25. return this
  26. }
  27. ESOne<T> jsonConvert(JsonConvert value) {
  28. this.jsonConvert = value
  29. return this
  30. }
  31. ESOne<T> clazz(Class<T> value) {
  32. this.clazz = value
  33. return this
  34. }
  35. ESOne<T> queryBuilder(QueryBuilderExecutor value) {
  36. this.qbe = value
  37. return this
  38. }
  39. ESOne<T> index(String value) {
  40. this.index = value
  41. return this
  42. }
  43. ESOne<T> hitExecutor(ESHitInfoExecutor<T> value) {
  44. this.de = value
  45. return this
  46. }
  47. T execute() {
  48. QueryBuilder qb = qbe.execute(null)
  49. SearchResponse scrollResp = esClient.getClient().prepareSearch(index)
  50. .setQuery(qb)
  51. .setSize(1)
  52. .execute()
  53. .actionGet()
  54. if (scrollResp.getHits().getTotalHits() == 0) {
  55. return null
  56. } else {
  57. SearchHit hit = scrollResp.getHits().getHits()[0]
  58. if (de != null) {
  59. return de.execute(hit)
  60. } else {
  61. return jsonConvert.convertFrom(clazz, hit.getSourceAsString())
  62. }
  63. }
  64. }
  65. }