简单实现ElasticSearch中REST风格CRUD

本文详细介绍如何使用Elasticsearch进行项目开发,包括创建和删除索引、修改数据、查询数据、批量操作等关键步骤。通过具体代码示例,展示如何利用REST客户端与Elasticsearch交互,实现高效的数据管理和检索。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、项目中需要依赖的ES包

      <dependency>
        <groupId>org.elasticsearch</groupId>
        <artifactId>elasticsearch</artifactId>
        <version>6.2.3</version>
      </dependency>
      <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>elasticsearch-rest-high-level-client</artifactId>
        <version>6.2.3</version>
      </dependency>
      <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.47</version>
      </dependency>

首先,得创建一个REST客户端

// 创建Rest客户端
  val client = new RestHighLevelClient(RestClient.builder(new HttpHost("192.168.20.132", 9200 ,"http") ))

 

2、创建索引

  def testIndex():Unit = {
    val jsonMap = new JSONObject()
    jsonMap.put("user", "AKUK")
    jsonMap.put("postDate", new Date())
    jsonMap.put("message", "trying out Elasticsearch")
    val request = new IndexRequest("posts","doc","1").source(jsonMap)
    val response = client.index(request)
    print(response.getResult)
  }

3、删除索引

def deleteIndex() : Unit = {
    // 设置要删除的索引名称
    val request = new DeleteIndexRequest("POSTS")
    request.timeout(TimeValue.timeValueMinutes(2))
    request.masterNodeTimeout(TimeValue.timeValueMinutes(1))
    request.indicesOptions(IndicesOptions.lenientExpandOpen)
    //同步执行
    val deleteIndexResponse = client.indices.delete(request)
    val acknowledged = deleteIndexResponse.isAcknowledged //是否所有节点都已确认请求
    print("是否所有的节点已经确认:"+acknowledged);

    //如果找不到索引,则会抛出ElasticsearchException:
    try {
      val request = new DeleteIndexRequest("does_not_exist")
      client.indices.delete(request)
    } catch {
      case exception: ElasticsearchException =>
        if (exception.status eq RestStatus.NOT_FOUND) {
          //如果没有找到要删除的索引,要执行某些操作
        }
    }

  }

4、修改数据

  def testUpdateIndexField() : Unit = {
    val request = new IndexRequest("posts","doc","1").source("user","AKUK")
    val response = client.index(request)
    print(response.getResult)
  }

5、查询数据

  /**
      521
      {"title":"In which order are my Elasticsearch queries executed?"}
      {"title":"In which order are my Elasticsearch queries executed?"}
      14
    */
  def getRequest() : Unit = {
    //
    {
      val l = System.currentTimeMillis()
      val request = new GetRequest("posts", "doc", "1")
      val response = client.get(request)
      println(System.currentTimeMillis() - l)
      //println(response.getSourceAsString)
      //println(response.getSourceInternal)
    }
    // 同步按条件批量查询
    {
      val request = new GetRequest("posts", "doc", "1")
      val includes = Array[String]("title")
      val emptyarray = Strings.EMPTY_ARRAY
      val context = new FetchSourceContext(true, includes, emptyarray)
      request.fetchSourceContext(context)
      val response1 = client.get(request)
      println(response1.getSourceAsString)
    }
    // 异步实现查询
    {
      import java.util.concurrent.CountDownLatch

      import org.elasticsearch.action.get.{GetRequest, GetResponse}
      import org.elasticsearch.action.{ActionListener, LatchedActionListener}

      val request = new GetRequest("posts", "doc", "1")
      //tag::get-execute-listener
      var listener = new ActionListener[GetResponse]() {
        override def onResponse(getResponse: GetResponse): Unit = {
          println(getResponse.getSourceAsString)
        }

        override def onFailure(e: Exception): Unit = {
          // <2>
        }
      }
      //end::get-execute-listener

      // Replace the empty listener by a blocking listener in test
      val latch = new CountDownLatch(1)
      listener = new LatchedActionListener[GetResponse](listener, latch)


      val l = System.currentTimeMillis()
      //tag::get-execute-async
      client.getAsync(request, listener)
      //Thread.sleep(3000)
      latch.await(30L, TimeUnit.SECONDS)
      //end::get-execute-async
      println(System.currentTimeMillis() - l)
    }
  }

6、批量操作

    /**eg.1
      * 1686
        OK
        OK
        3003

       eg.2
        1147
        OK
        OK
        29
      */
def testBulk() : Unit = {
    val request = new BulkRequest()
    val one = new IndexRequest("posts", "doc", "1").source(XContentType.JSON, "title", "In which order are my Elasticsearch queries executed?")
    val two = new IndexRequest("posts", "doc", "2").source(XContentType.JSON, "title", "Current status and upcoming changes in Elasticsearch")
    val three = new IndexRequest("posts", "doc", "3").source(XContentType.JSON, "title", "The Future of Federated Search in Elasticsearch")

    request.add(one, two, three)
    val l = System.currentTimeMillis()
    // 同步操作
    val response = client.bulk(request)
    println(System.currentTimeMillis() - l)
    println(response.status())

    val s = System.currentTimeMillis()
    var listener = new ActionListener[BulkResponse]() {
      override def onResponse(getResponse: BulkResponse): Unit = {
        println(getResponse.status())
      }

      override def onFailure(e: Exception): Unit = {
        // <2>
      }
    }
    //end::get-execute-listener

    // Replace the empty listener by a blocking listener in test
    val latch = new CountDownLatch(1)
    listener = new LatchedActionListener[BulkResponse](listener, latch)
    // 异步操作
    client.bulkAsync(request, listener)
    //Thread.sleep(3000)
    latch.await(30L, TimeUnit.SECONDS)
    println(System.currentTimeMillis() - s)
    
  }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值