Elastic Search使用Spring Boot集成ES使用JAVA代码进行操作------Elastic Search

#AI发展下的伦理挑战,应当如何应对?#
GET users/_search

GET /users/_search
{
  "query": {
    "match_all": {}
  }
}

GET users/_search

GET /users/_search
{
  "query": {
    "match_all": {}
  }
}

{
  "took" : 1,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 1,
      "relation" : "eq"
    },
    "max_score" : 1.0,
    "hits" : [
      {
        "_index" : "users",
        "_type" : "_doc",
        "_id" : "1",
        "_score" : 1.0,
        "_source" : {
          "age" : 16,
          "gender" : "女",
          "username" : "Rose"
        }
      }
    ]
  }
}

 {
  "took" : 1,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 1,
      "relation" : "eq"
    },
    "max_score" : 1.0,
    "hits" : [
      {
        "_index" : "users",
        "_type" : "_doc",
        "_id" : "1",
        "_score" : 1.0,
        "_source" : {
          "age" : 16,
          "gender" : "女",
          "username" : "Rose"
        }
      }
    ]
  }
}

package com.alatus.search.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.HttpAsyncResponseConsumerFactory;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import static com.alibaba.nacos.api.common.Constants.TOKEN;

@Configuration
public class MallElasticSearchConfig {
    public static final RequestOptions COMMON_OPTIONS;

    static {
        RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
//        builder.addHeader("Authorization", "Bearer " + TOKEN);
//        builder.setHttpAsyncResponseConsumerFactory(
//                new HttpAsyncResponseConsumerFactory.HeapBufferedResponseConsumerFactory(30 * 1024 * 1024 * 1024));
        COMMON_OPTIONS = builder.build();
    }

    //    编写配置
//    给容器中注入一个RestHighLevelClient
    @Bean
    public RestHighLevelClient esRestClient(){
        return new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("192.168.56.10",9200,"http")
                )
        );
    }
}
package com.alatus.search.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.HttpAsyncResponseConsumerFactory;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import static com.alibaba.nacos.api.common.Constants.TOKEN;

@Configuration
public class MallElasticSearchConfig {
    public static final RequestOptions COMMON_OPTIONS;

    static {
        RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
//        builder.addHeader("Authorization", "Bearer " + TOKEN);
//        builder.setHttpAsyncResponseConsumerFactory(
//                new HttpAsyncResponseConsumerFactory.HeapBufferedResponseConsumerFactory(30 * 1024 * 1024 * 1024));
        COMMON_OPTIONS = builder.build();
    }

    //    编写配置
//    给容器中注入一个RestHighLevelClient
    @Bean
    public RestHighLevelClient esRestClient(){
        return new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("192.168.56.10",9200,"http")
                )
        );
    }
}
package com.alatus.search;

import com.alatus.search.config.MallElasticSearchConfig;
import com.alibaba.fastjson.JSON;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.IOException;

@RunWith(SpringRunner.class)
@SpringBootTest
public class TestLoad {
    @Autowired
    private RestHighLevelClient client;
    @Test
    public void load(){
        System.out.println(client);
    }
    @Test
    public void index() throws IOException {
        IndexRequest request = new IndexRequest("users");
        request.id("1");
        request.source("username","Jack","age",18,"gender","男");
        String jsonString = JSON.toJSONString(new User("Rose", 18, "女"));
        request.source(jsonString, XContentType.JSON);
//        执行操作
        IndexResponse index = client.index(request, MallElasticSearchConfig.COMMON_OPTIONS);
        System.out.println(index);
    }
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    class User{
        private String username;
        private Integer age;
        private String gender;
    }
}
package com.alatus.search;

import com.alatus.search.config.MallElasticSearchConfig;
import com.alibaba.fastjson.JSON;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.IOException;

@RunWith(SpringRunner.class)
@SpringBootTest
public class TestLoad {
    @Autowired
    private RestHighLevelClient client;
    @Test
    public void load(){
        System.out.println(client);
    }
    @Test
    public void index() throws IOException {
        IndexRequest request = new IndexRequest("users");
        request.id("1");
        request.source("username","Jack","age",18,"gender","男");
        String jsonString = JSON.toJSONString(new User("Rose", 18, "女"));
        request.source(jsonString, XContentType.JSON);
//        执行操作
        IndexResponse index = client.index(request, MallElasticSearchConfig.COMMON_OPTIONS);
        System.out.println(index);
    }
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    class User{
        private String username;
        private Integer age;
        private String gender;
    }
}
  • 6
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用 Spring Boot Starter Data Elasticsearch 可以轻松地在 Spring Boot 应用中集成 Elasticsearch。以下是使用步骤: 1. 添加依赖:在你的 pom.xml 文件中添加 Spring Boot Starter Data Elasticsearch 依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> ``` 2. 配置连接:在应用的配置文件中,配置 Elasticsearch 的连接信息。例如,在 application.properties 文件中添加以下配置: ```properties spring.data.elasticsearch.cluster-nodes=localhost:9200 ``` 3. 创建实体类:创建一个与 Elasticsearch 索引文档对应的实体类,并使用注解进行映射。例如: ```java import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; @Document(indexName = "myindex", type = "mytype") public class MyDocument { @Id private String id; private String name; // Getters and setters } ``` 在上面的示例中,`@Document` 注解用于指定索引名称和类型,`@Id` 注解表示文档的唯一标识。 4. 创建仓库接口:创建一个继承自 ElasticsearchRepository 的接口,用于定义与 Elasticsearch 进行交互的方法。例如: ```java import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; public interface MyDocumentRepository extends ElasticsearchRepository<MyDocument, String> { List<MyDocument> findByName(String name); } ``` 在上面的示例中,`ElasticsearchRepository` 提供了一些基本的 CRUD 操作,你还可以定义自己的查询方法。 5. 使用仓库接口:在需要使用 Elasticsearch 的地方,通过注入仓库接口来进行操作。例如,在一个服务类中注入 `MyDocumentRepository` 并使用它执行查询: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class MyService { @Autowired private MyDocumentRepository repository; public List<MyDocument> searchByName(String name) { return repository.findByName(name); } } ``` 以上就是使用 Spring Boot Starter Data Elasticsearch 的基本步骤。你可以根据自己的需求,进行更多的配置和操作,包括自定义查询、分页等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值