Java连接Elasticsearch5.X的三种方式并附带代码(增删改查)

Elasticsearch官方为Java提供了三种客户端API:

  1. TransportClient:这种方式通过TCP与Elasticsearch服务进行交互。还有 transport-netty4-client 的客户端(使用9300端口)
  2. Java Low Level REST Client:低级别的REST客户端,使用Apache HttpClient进行HTTP调用,简单封装了一下,通过http与集群交互,需要自己处理请求和响应,用户需自己编组请求JSON串,及解析响应JSON串。兼容所有ES版本。
  3. Java High Level REST Client:高级别的REST客户端,基于低级别的REST客户端,提供了面向方法的API,增加了编组请求JSON串、解析响应JSON串等相关api。使用的版本需要保持和ES服务端的版本一致,否则会有版本问题。同时请求参数和响应参数使用了elasticsearch定义的实体,方便从Java API Client迁移,Java High Level Rest Client完成elasticsearch请求响应实体转换为Java Low Level Rest Client的请求响应。即解决了Java API Client兼容问题,又解决了Java Low Level Rest Client封装使用问题(使用9200端口)
    官方文档

9200端口是用于Http协议访问的,如果通过客户端访问需要通过9300端口才可以访问

TranportClient

预备工作

依赖

<dependencies>

    <!--引入fastjson-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.60</version>
    </dependency>

    <!-- elasticsearch依赖2.x的log4j -->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-api</artifactId>
      <version>2.8.2</version>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-core</artifactId>
      <version>2.8.2</version>
    </dependency>
    <!-- junit单元测试 -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>
      <!-- elasticsearch依赖 -->
      <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>transport</artifactId>
        <version>5.6.4</version>
      </dependency>
  </dependencies>

实体类,这个是我们封装实体类进行添加的时候使用

/**
 * 创建新Document时候可以用这种实体类的方式
 */
public class Article {
    private Long id;
    private String title;
    private String content;

    //getter and setter

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}

具体的增删改查操作

public class ESTranTest {
    /**
     * 创建索引
     */
    @Test
    public void testCreateIndex() throws UnknownHostException {
        TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY).addTransportAddress(
                new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
        //创建索引 blog5
        CreateIndexResponse indexResponse = transportClient.admin().indices().prepareCreate("blog5").get();

        //确认输出:true
        System.out.println(indexResponse.isAcknowledged());
        //true
        System.out.println(indexResponse.isShardsAcked());
        transportClient.close();
    }

    /**
     * 删除索引
     */
    @Test
    public void testDelIndex() throws Exception {
        //创建Client连接对象
        TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY)
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));

        //删除名称为blog5的索引
        //多数据
        //DeleteIndexResponse deleteIndexResponse = transportClient.admin().indices() .prepareDelete("blog5", "blog").get();//#####
        //对象传参
        DeleteIndexResponse deleteIndexResponse = transportClient.admin().indices().delete(new DeleteIndexRequest("blog5")).get();
        //true
        System.out.println(deleteIndexResponse.isAcknowledged());
        transportClient.close();
    }


    /**
     * 创建mapping
     */
    @Test
    public void testCreateMapping() throws Exception {
        TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY)
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));

        //exists方法,判断索引是否存在
        IndicesExistsResponse indicesExistsResponse = transportClient.admin().indices().exists(new IndicesExistsRequest("blog5")).get();
        //索引存在:false
        System.out.println("索引存在:" + indicesExistsResponse.isExists());
        //判断索引是否存在
        if (!indicesExistsResponse.isExists()) {
            //不存在则创建索引 blog5
            CreateIndexResponse createIndexResponse = transportClient.admin().indices().prepareCreate("blog5").get();
            //创建索引:true
            System.out.println("创建索引:" + createIndexResponse.isAcknowledged());
        }
        //添加映射
        /**  格式:
         "mappings": {
         "article": {
         "properties": {
         "id": {
         "store": true,
         "type": "long"
         },
         "title": {
         "store": true,
         "type": "text"
         },
         "content": {
         "store": true,
         "type": "text"
         }
         }
         } */
        XContentBuilder xContentBuilder = XContentFactory.jsonBuilder()
                .startObject()
                .startObject("article")
                .startObject("properties")
                .startObject("id").field("store", true).field("type", "long").endObject()
                .startObject("title").field("store", true).field("type", "text").endObject()
                .startObject("content").field("store", true).field("type", "text").endObject()
                .endObject()
                .endObject()
                .endObject();
        System.out.println(xContentBuilder.toString());
        //创建映射,映射到索引blog5、类型article上
        PutMappingRequest putMappingRequest = Requests.putMappingRequest("blog5").type("article").source(xContentBuilder);

        PutMappingResponse putMappingResponse = transportClient.admin().indices().putMapping(putMappingRequest).get();
        //true
        System.out.println(putMappingResponse.isAcknowledged());

        transportClient.close();
    }


    /**
     * 创建Document
     *
     * @throws Exception
     */
    @Test
    public void testCreateDocument() throws Exception {
        TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY)
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));

        //创建文档信息
        XContentBuilder xContentBuilder = XContentFactory.jsonBuilder()
                .startObject()
                .field("id", 3L)
                .field("title", "ElasticSearch是一个基于Lucene的搜索服务器")
                .field("content", "它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。Elasticsearch是" + "用Java开发的,并作为Apache许可条款下的开放源码发布,是当前流行的企业级搜索引擎")
                .endObject();
        //建立文档对象
        /**
         * 参数一 blog1:表示索引对象
         * 参数二 article:类型
         * 参数三 1:建立id */
        IndexResponse indexResponse = transportClient.prepareIndex("blog5", "article", "3").setSource(xContentBuilder).get();
        //CREATED
        System.out.println(indexResponse.status());
        transportClient.close();
    }


    /**
     * 通过一个实体对象创建json方便很多
     *
     * @throws Exception
     */
    @Test
    public void testCreateDocumentByBean() throws Exception {
        TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY)
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));

        //描述json 数据
        //{id:xxx, title:xxx, content:xxx}
        Article article = new Article();
        article.setId(2L);
        article.setTitle("ElasticSearch是一个基于Lucene的搜索服务器22");
        article.setContent("它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口22");
        //转成String类型
        String jsonStr = JSON.toJSONString(article);
        //建立文档
        IndexResponse indexResponse = transportClient.prepareIndex("blog5", "article", String.valueOf(article.getId())).setSource(jsonStr).get();
        //CREATED
        System.out.println(indexResponse.status());
        transportClient.close();
    }

    /**
     * 这是基于transportClient.prepareUpdate这种方法进行更新的
     *
     * @throws Exception
     */
    @Test
    public void testUpdateDocumentByUpdate() throws Exception {
        TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY)
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));

        Article article = new Article();
        article.setId(2L);
        article.setTitle("Edsfsdf基于Lucene的搜索服务器2222441111");
        article.setContent("基胜多负少的水电费于RESTful web接口22334");

        String jsonStr = JSON.toJSON(article).toString();
        //jsonStr={"id":2,"title":"Edsfsdf基于Lucene的搜索服务器222244","content":"基胜多负少的水电费于RESTful web接口22334"}
        System.out.println("jsonStr=" + jsonStr);

        //修改内容
        UpdateResponse updateResponse = transportClient.prepareUpdate("blog5", "article", String.valueOf(article.getId())).setDoc(jsonStr).get();
        //OK
        System.out.println(updateResponse.status());
        transportClient.close();
    }

    /**
     * 这是transportClient.update这种方法进行更新的
     *
     * @throws Exception
     */
    @Test
    public void testUpdateDocumentByUpdateRequest() throws Exception {
        TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY)
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
        Article article = new Article();
        article.setId(2L);
        article.setTitle("什么玩意这是更新以后的");
        article.setContent("确实是更新以后的哈你看看对不对");
        UpdateResponse updateResponse = transportClient.update(new UpdateRequest("blog5", "article", String.valueOf(article.getId())).doc(JSON.toJSONString(article))).get();
        System.out.println(updateResponse.status());
        transportClient.close();
    }


    /**
     * 删除Document
     *
     * @throws Exception
     */
    @Test
    public void testDeleteDocument() throws Exception {
        TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY)
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));

        // prepareDelete 删除数据
        DeleteResponse deleteResponse = transportClient.prepareDelete("blog5", "article", "2").get();
        System.out.println(deleteResponse.status());
        transportClient.close();
    }


    /**
     * 根据查询条件进行删除数据
     */
    @Test
    public void elasticsearchDeleteByQuery() throws Exception {
        TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY)
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));

        BulkByScrollResponse response = DeleteByQueryAction.INSTANCE.newRequestBuilder(transportClient)
                // 指定查询条件,matchQuery是name的值text里面包括了这个内容就进行删除。默认使用标准分词器。
                .filter(QueryBuilders.matchQuery("content", "Apache"))
                // 指定索引名称
                .source("blog5").get();
        // 获取到删除的个数
        long deleted = response.getDeleted();
        // 打印输出删除的个数
        System.out.println(deleted);
        //1
    }


    /**
     * 异步删除
     * 监听,如果真正删除以后进行回调,打印输出删除确认的消息。
     */
    @Test
    public void elasticsearchDeleteByQueryAsync() throws UnknownHostException {

        TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY)
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
        DeleteByQueryAction.INSTANCE.newRequestBuilder(transportClient)
                .filter(QueryBuilders.matchQuery("id", 2L))
                .source("blog5")
                .execute(new ActionListener<BulkByScrollResponse>() {
                    // 删除以后的方法回调
                    @Override
                    public void onResponse(BulkByScrollResponse response) {
                        // 返回删除的个数
                        long deleted = response.getDeleted();
                        System.out.println("数据删除完毕!");
                        // 打印删除的个数
                        System.out.println("数据删除的个数: " + deleted);
                    }

                    @Override
                    public void onFailure(Exception e) {
                        // 失败打印异常信息
                        e.printStackTrace();
                    }
                });

        // 先打印输出,正常执行完毕。再执行异步监听删除数据。
        try {
            System.out.println("开始异步删除操作!");
            // 休眠10秒钟
            Thread.sleep(5000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询全部
     */
    @Test
    public void testFindAll() throws Exception {
        //创建客户端访问对象
        TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY)
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));

        //QueryBuilders.matchAllQuery(),查询全部
        SearchResponse response = transportClient.prepareSearch("blog5").setTypes("article")
                .setQuery(QueryBuilders.matchAllQuery())
                .get();
        //获取搜索结果
        SearchHits hits = response.getHits();
        System.out.println(hits.getTotalHits());
        //遍历结果
        SearchHit[] hits1 = hits.getHits();
        for (SearchHit hit : hits1) {
            System.out.println(hit.getSourceAsString());
        }
        transportClient.close();
    }

    /**
     * 根据id号进行条件查询
     * @throws Exception
     */
    @Test
    public void testFindById() throws Exception {
        //创建客户端访问对象
        TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY)
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));

        //按条件进行查询
        SearchResponse searchResponse = transportClient.prepareSearch("blog5")
                .setTypes("article").setQuery(QueryBuilders.matchQuery("id", 2)).get();
        //获取搜索结果
        SearchHits hits = searchResponse.getHits();
        //遍历结果
        SearchHit[] hits1 = hits.getHits();
        for (SearchHit hit : hits1) {
            System.out.println(hit.getSourceAsString());
        }
        transportClient.close();
    }

}

Java Low Level REST Client

预备工作

        <!--引入fastjson-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.60</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-client</artifactId>
            <version>5.6.4</version>
        </dependency>

具体的增删改查代码

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpHost;
import org.apache.http.entity.ContentType;
import org.apache.http.nio.entity.NStringEntity;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.junit.Test;

import java.io.IOException;
import java.util.Collections;
import java.util.Map;

/**
 * @author td
 */
public class Client {

    /**
     * 新建Document
     *
     * @throws IOException
     */
    @Test
    public void testCreateDocument() throws IOException {
        // 建立连接  注意9200端口  9300是tcp内部通信的
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200, "http")).build();
        //描述json 数据
        //{id:xxx, title:xxx, content:xxx}
        Article article = new Article();
        article.setId(2L);
        article.setTitle("ElasticSearch是一个基于Lucene的搜索服务器22");
        article.setContent("它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口22");

        Map<String, String> params = Collections.emptyMap();
        Response put = restClient.performRequest("PUT", "/blog5/article/4",params
                ,new NStringEntity(JSON.toJSONString(article), ContentType.APPLICATION_JSON));
        // System.out.println(JSON.toJSONString(article));
        // System.out.println(new NStringEntity(JSON.toJSONString(article)));
        System.out.println(put.getRequestLine());
        restClient.close();
    }

    /**
     * 更新操作
     *
     * @throws Exception
     */
    @Test
    public void testUpdateDocumentByUpdate() throws Exception {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200, "http")).build();

        Article article = new Article();
        article.setId(2L);
        article.setTitle("ElasticSearch是fdsfsdfsd22");
        article.setContent("它提供了一fsdsdfsdf多用户能力的全文搜索引擎,基于RESTful web接口22");

        Map<String, String> params = Collections.emptyMap();
        Response put = restClient.performRequest("POST", "/blog5/article/3",params
                ,new NStringEntity(JSON.toJSONString(article),ContentType.APPLICATION_JSON));
        System.out.println(put.getRequestLine());
    }

    /**
     * 查找特定的Document
     *
     * @throws IOException
     */
    @Test
    public void testFindOne() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200, "http")).build();

        Response get = restClient.performRequest("GET", "/blog5/article/4", Collections.<String, String>emptyMap());
        String s = EntityUtils.toString(get.getEntity());
        System.out.println(s);
        restClient.close();
    }

    /**
     * 查找全部的Document
     *
     * @throws IOException
     */
    @Test
    public void testFindAll() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200, "http")).build();

        Response get = restClient.performRequest("GET", "/blog5/article/_search", Collections.<String, String>emptyMap());
        String s = EntityUtils.toString(get.getEntity());
        System.out.println(s);
        restClient.close();
    }

    /**
     * 删除指定id的Document
     *
     * @throws IOException
     */
    @Test
    public void deleteById() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200, "http")).build();

        Response get = restClient.performRequest("DELETE", "/blog5/article/1", Collections.<String, String>emptyMap());
        String s = EntityUtils.toString(get.getEntity());
        System.out.println(s);
        restClient.close();
    }
}

Java High Level REST Client

因为High就是对low的封装,就不展开说了,直接说High

预备工作

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    <!-- elasticsearch依赖5.x的log4j -->
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>2.8.2</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.8.2</version>
    </dependency>
    <!--引入fastjson-->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.60</version>
    </dependency>
    <!--引入rest-high-level-client-->
    <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>elasticsearch-rest-high-level-client</artifactId>
        <version>5.6.4</version>
    </dependency>

实体类

/**
 * 创建新Document时候可以用这种实体类的方式
 */
public class Article {
    private Long id;
    private String title;
    private String content;

    //getter and setter

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}

具体的增删改查代码:

public class HighLevel {
    /**
     * 新建Document
     *
     * @throws IOException
     */
    @Test
    public void testCreateDocument() throws IOException {
        // 建立连接  注意9200端口  9300是tcp内部通信的
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200, "http")).build();
        RestHighLevelClient client = new RestHighLevelClient(restClient);
        //创建文档信息
        XContentBuilder xContentBuilder = XContentFactory.jsonBuilder().startObject().field("id", 3L).field("title", "1121211ElastisdfsdfsdfsdfsdcSearch是一个基于Lucene的搜索服务器").field("content", "它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。Elasticsearch是" + "用Java开发的,并作为Apache许可条款下的开放源码发布,是当前流行的企业级搜索引擎").endObject();
        //  index名 type名 id号
        IndexRequest request = new IndexRequest("blog", "article", "1").source(xContentBuilder);
        IndexResponse response = client.index(request);
        System.out.println(response.status());
        restClient.close();
    }

    /**
     * 通过实体类进行添加Document
     *
     * @throws Exception
     */

    @Test
    public void testCreateDocumentByBean() throws Exception {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200, "http")).build();
        RestHighLevelClient client = new RestHighLevelClient(restClient);
        //描述json 数据
        //{id:xxx, title:xxx, content:xxx}
        Article article = new Article();
        article.setId(2L);
        article.setTitle("ElasticSearch是一个基于Lucene的搜索服务器22");
        article.setContent("它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口22");
        //转成String类型
        String jsonStr = JSON.toJSONString(article);
        //建立文档
        IndexRequest request = new IndexRequest("blog", "article", "2").source(jsonStr, XContentType.JSON);
        IndexResponse response = client.index(request, new BasicHeader("header", "value"));
        System.out.println(response.status());
        restClient.close();
    }

    /**
     * 更新操作
     *
     * @throws Exception
     */
    @Test
    public void testUpdateDocumentByUpdate() throws Exception {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200, "http")).build();
        RestHighLevelClient client = new RestHighLevelClient(restClient);
        Article article = new Article();
        article.setId(2L);
        article.setTitle("Edsfsdf基于Lucene的搜索服务器2222441111");
        article.setContent("基胜多负少的水电费于RESTful web接口22334");

        String jsonStr = JSON.toJSON(article).toString();
        System.out.println("jsonStr=" + jsonStr);

        //修改内容
        UpdateRequest request = new UpdateRequest("blog", "article", "2").doc(jsonStr, XContentType.JSON);
        UpdateResponse update = client.update(request);
        //OK
        System.out.println(update.status());
        restClient.close();
    }


    /**
     * 删除Document
     *
     * @throws Exception
     */
    @Test
    public void testDeleteDocument() throws Exception {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200, "http")).build();
        RestHighLevelClient client = new RestHighLevelClient(restClient);
        //  删除数据
        DeleteRequest deleteRequest = new DeleteRequest("blog", "article", "2");
        DeleteResponse delete = client.delete(deleteRequest);
        System.out.println(delete.status());
        restClient.close();
    }

    /**
     * 查询blog表下的所有Document
     */
    @Test
    public void testFindAll() throws Exception {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200, "http")).build();
        RestHighLevelClient client = new RestHighLevelClient(restClient);

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
        SearchRequest searchRequest = new SearchRequest("blog").source(searchSourceBuilder);

        SearchResponse response = client.search(searchRequest);
        SearchHits hits = response.getHits();
        for (SearchHit searchHit : hits.getHits()) {
            System.out.println(searchHit.getSourceAsString());
        }

        restClient.close();
    }

    /**
     * 查找特定的Document
     *
     * @throws IOException
     */
    @Test
    public void testFindOne() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200, "http")).build();
        RestHighLevelClient client = new RestHighLevelClient(restClient);

        GetRequest getRequest = new GetRequest("blog", "article", "1");
        GetResponse getResponse = client.get(getRequest);

        System.out.println(getResponse.getSourceAsString());
        restClient.close();
    }


    /**
     * SearchSourceBuilder().query的方法进行查询
     */
    @Test
    public void testFindById() throws Exception {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200, "http")).build();
        RestHighLevelClient client = new RestHighLevelClient(restClient);

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder().query(QueryBuilders.matchQuery("content", "22"));
        SearchRequest searchRequest = new SearchRequest("blog").source(searchSourceBuilder);

        SearchResponse response = client.search(searchRequest);
        SearchHits hits = response.getHits();
        for (SearchHit searchHit : hits.getHits()) {
            System.out.println(searchHit.getSourceAsString());
        }

        restClient.close();
    }
}

可能遇到的问题 log4j的问题

在resource目录下配置log4j.properties

log4j.rootLogger=INFO,Console

log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
log4j.appender.Console.Threshold=DEBUG
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%d]%l%5p:%m%n

log4j.appender.DebugFile=org.apache.log4j.RollingFileAppender
log4j.appender.DebugFile.File=../log/debugFile.log
#log4j.appender.DebugFile.File=debugFile.log
log4j.appender.DebugFile.Append=true
log4j.appender.DebugFile.Threshold=DEBUG
log4j.appender.DebugFile.layout=org.apache.log4j.PatternLayout
log4j.appender.DebugFile.layout.ConversionPattern=[%d]%l%5p:%m%n
log4j.appender.DebugFile.MaxFileSize=20MB
log4j.appender.DebugFile.MaxBackupIndex=10

log4j.logger.com.ibatis=DEBUG
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG

log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Connection = INFO
log4j.logger.java.sql.Statement = DEBUG
log4j.logger.java.sql.PreparedStatement = DEBUG
log4j.logger.java.sql.ResultSet = DEBUG

log4j.logger.com.yuetao=DEBUG

第二个配置文件 log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
    <Appenders>
        <Console name="STDOUT" target="SYSTEM_OUT">
            <PatternLayout pattern="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/>
        </Console>
        <RollingFile name="RollingFile" fileName="logs/strutslog1.log"
                     filePattern="logs/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz">
            <PatternLayout>
                <Pattern>%d{MM-dd-yyyy} %p %c{1.} [%t] -%M-%L- %m%n</Pattern>
            </PatternLayout>
            <Policies>
                <TimeBasedTriggeringPolicy />
                <SizeBasedTriggeringPolicy size="1 KB"/>
            </Policies>
            <DefaultRolloverStrategy fileIndex="max" max="2"/>
        </RollingFile>
    </Appenders>
    <Loggers>
        <Logger name="com.opensymphony.xwork2" level="WAN"/>
        <Logger name="org.apache.struts2" level="WAN"/>
        <Root level="warn">
            <AppenderRef ref="STDOUT"/>
        </Root>
    </Loggers>

</Configuration>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值