Es在SpringBoot中的使用

新建

<!-- SpringBoot默认使用SpringData ElasticSearch模块进行操作-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>

SpringBoot支持两种技术来和ES交互
1、Jest
需要导入jest的工具包(io.searchbox.client.JestClient)
2、SpringData ElasticSearch
1)Client 结点信息:ClusterNodes;Clustername
2)ElasticSearchTemplate操作es
3)也可以编写ElasticSearchRepository的子接口来操作es
3、Rest
需要导入Rest的工具包(org.elasticsearch.client.RestClient)
在这里插入图片描述

Jest

导入jest的maven包

        <dependency>
            <groupId>io.searchbox</groupId>
            <artifactId>jest</artifactId>
            <version>6.3.1</version>
        </dependency>

我们看到Jest的Properties中默认了uris为localhost。首先我们需要修改一下这里

@ConfigurationProperties(prefix = "spring.elasticsearch.jest")
public class JestProperties {

	/**
	 * Comma-separated list of the Elasticsearch instances to use.
	 */
	private List<String> uris = new ArrayList<>(Collections.singletonList("http://localhost:9200"));
@Test
    public void test()
    {
        Article article = new Article();
        article.setId(1);
        article.setAuthor("san");
        article.setTitle("newsdaily");
        article.setContent("hello boy and girls");

        Index index = new Index.Builder(article).index("atlyb").type("news").id("1").build();
        try {
            jestClient.execute(index);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

可以看到已经插入进去的数据了
在这里插入图片描述
书写一个获取的测试

@Test
    public void search()
    {
        String json="{\n" +
                "    \"query\" : {\n" +
                "        \"match\" : {\n" +
                "            \"content\" : \"hello\"\n" +
                "        }\n" +
                "    }\n" +
                "}";
        Search builder = new Search.Builder(json).addIndex("atlyb").addType("news").build();
        try {
            SearchResult execute = jestClient.execute(builder);

            System.out.println(execute);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

可以看到结果已经得到获取结果
要想获取其他的用法可以参考jest的github文档——Jest文档

SpringDataES

按照最新的SpringData的要求我们先写一个配置文件

public class Esconfig {
    private static TransportClient client;

    private static String clusterName;
    private static List<String> clusterNodes;

    static {
        clusterName = "docker-cluster";
        clusterNodes = Arrays.asList("http://119.3.223.115:9300");
    }

    private Esconfig() {
    }

    public static Client getClient() throws UnknownHostException {
        Settings settings = Settings.builder().put("cluster.name", clusterName).build();
        client = new PreBuiltTransportClient(settings);
        for (String node : clusterNodes) {
            URI host = URI.create(node);
            client.addTransportAddress(new TransportAddress(InetAddress.getByName(host.getHost()), host.getPort()));
        }
        return client;
    }

    public static void close() {
        client.close();
    }
}

我们用多线程的方法一次性插入50条数据

    private static int count = 50;
    private static ExecutorService cachedThreadPool = Executors.newFixedThreadPool(count);


    public void SpringBootes(AtomicLong productId,Client client){
        Article article = new Article();
        String content=productId.incrementAndGet()+"32 234gfd dhfgjljadhadhflskdfjqlkjio返回时间的反馈了和数据1";
        article.setId((int)productId.get());
        article.setAuthor("si");
        article.setTitle("goodDaily");
        article.setContent(content);


        System.out.println("====================="+article.getId());
        Map<String,Object> map = new HashMap<>();
        map.put("json",JSON.toJSONString(article));
        IndexResponse response = client.prepareIndex("spring-data","article", article.getId().toString())
                .setSource(map)
                .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE)
                .get();
        System.out.println(response);
    }

    @Test
    public void Test01(){
        try {
            System.out.println("es client init start");
            long start = System.currentTimeMillis();
            Client client = Esconfig.getClient();
            System.out.println("es client init end:"+(System.currentTimeMillis()-start)+"ms");

            System.out.println("====================test start");
            start = System.currentTimeMillis();
            AtomicLong productId=new AtomicLong();
            CountDownLatch countDownLatch = new CountDownLatch(count);
            for (int i = 0; i < count; i++) {
                cachedThreadPool.execute(new Runnable() {
                    @Override
                    public void run() {
                        System.out.println(1);
                        SpringBootes(productId, client);
                        countDownLatch.countDown();
                    }
                });
            }

            countDownLatch.await();
            System.out.println("总耗时:" + (System.currentTimeMillis()-start) + "ms");

            cachedThreadPool.shutdown();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

运行结束后
在这里插入图片描述
精准获取

@Test
    public void Test02(){
        try {
            Client client = Esconfig.getClient();
            GetRequest getRequest=new GetRequest("spring-data","article","2");

            ActionFuture<GetResponse> getResponse =  client.get(getRequest);

            System.out.println(getResponse.actionGet().getSourceAsString());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

在这里插入图片描述
查询获取

    @Test
    public void Test03(){
        Client client = null;
        try {
            client = Esconfig.getClient();
            SearchRequest searchRequest=new SearchRequest("spring-data");
            searchRequest.types("article");

            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            //获取全部数据
            //searchSourceBuilder.query(QueryBuilders.matchAllQuery());

            //查询包含关键词字段的文档:如下,表示查询出来所有包含content字段且content字段包含5值的文档
            searchSourceBuilder.query(QueryBuilders.termQuery("Content", "2832"));

            searchRequest.source(searchSourceBuilder);

            ActionFuture<SearchResponse> searchResponseActionFuture = client.search(searchRequest);
            Map<String,Article> map = new HashMap<>();
            //searchResponseActionFuture.actionGet().getHits().getCollapseValues();
            System.out.println(searchResponseActionFuture.actionGet());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值