ElasticSearch cluster API operation

Preliminary preparation

First of all, the packages that pom needs to import are as follows:

 <dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>6.0.0</version>
</dependency>
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>transport</artifactId>
    <version>6.0.0</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-to-slf4j</artifactId>
    <version>2.12.1</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.30</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>1.7.5</version>
</dependency>
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.10.1</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.10.1</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.10.1</version>
</dependency>

Because the following test methods are many, and each time the client client needs to be created and closed, it is cumbersome, so in order to simplify the code. Propose separately

 public static PreBuiltTransportClient client;

 @Before
 public void init() throws Exception {
    
    
     // 创建一个配置文件
     Settings settings = Settings.builder()
             .put("cluster.name", "test")
             .build();
     client = new PreBuiltTransportClient(settings);
     // 集群的ip以及端口
     client.addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.135.237"), 9301));
     client.addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.135.237"), 9302));
     client.addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.135.237"), 9303));
 }

 @After
 public void close() {
    
    
     client.close();
 }

In this way, when a method is executed, the Before method will be executed first, then the method will be executed, and finally the After method will be executed.

Create index

@Test
public void testClusterCreateIndex() throws Exception {
    
    
    // admin():获取Admin API,用indices()方法对索引进行操作
    client.admin().indices().prepareCreate("cluster")
            .get();
}

Create mapping

@Test
public void testCreateMapping() throws Exception {
    
    
    XContentBuilder doc = XContentFactory.jsonBuilder()
            .startObject()
                .startObject("test-type")
                    .startObject("properties")
                        .startObject("id")
                            .field("type", "long")
                            .field("store", true)
                        .endObject()
                        .startObject("title")
                            .field("type", "text")
                            .field("store", true)
                        .endObject()
                        .startObject("content")
                            .field("type", "text")
                            .field("store", true)
                        .endObject()
                    .endObject()
                .endObject()
            .endObject();
    // 把mapping信息设置到索引库当中
    PutMappingResponse response = client.admin().indices()
            // 设置要做映射的索引
            .preparePutMapping("cluster")
            // 设置要做映射的type
            .setType("test-type")
            // mapping 信息
            .setSource(doc)
            // 执行
            .get();
    System.out.println(response.isAcknowledged());
}

As a result, you can use postman to check and compare:
(In fact, it doesn’t need to be so cumbersome to write, because the attribute ES such as store is by default true, and we don’t need to write it out specifically, just to let everyone better see the mapping added A structure is written like this)
Insert picture description here

Insert data

Insert using XContentFactory

@Test
public void testInsertDocument() throws Exception {
    
    
    XContentBuilder doc = XContentFactory.jsonBuilder()
            // 代表一个开始
            .startObject()
                .field("id", "2")
                .field("title", "wow,so good")
                .field("content", "233333333333333355555555555555")
            // 代表结束
            .endObject();
    client.prepareIndex()
            // 设置索引名称
            .setIndex("cluster")
            // 设置ype
            .setType("test-type")
            .setId("1")
            // 获取数据文档
            .setSource(doc)
            //执行
            .get();
}

Create native objects and insert into JSON

For example, if you need to insert the attributes of the Article object into ES, you must first create an object.
Step 1: Create the Article class:

public class Article {
    
    
    private int id;
    private String title;
    private long content;

    public int getId() {
    
    
        return id;
    }

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

    public String getTitle() {
    
    
        return title;
    }

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

    public long getContent() {
    
    
        return content;
    }

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

The second step:

@Test
public void testInsertDocument2() throws Exception {
    
    
    Article article = new Article();
    article.setId(101);
    article.setTitle("hello");
    article.setContent(666666666);
    ObjectMapper objectMapper = new ObjectMapper();
    String doc = objectMapper.writeValueAsString(article);

    client.prepareIndex()
            // 设置索引名称
            .setIndex("cluster")
            // 设置ype
            .setType("test-type")
            .setId("1")
            .setSource(doc, XContentType.JSON)
            .get();
}

Inquire

Ready to work

Write a query method: QueryBuilder is the incoming parameter

 public void search(QueryBuilder queryBuilder) {
    
    
        // 执行查询
        SearchResponse response = client.prepareSearch("cluster")
                .setTypes("test-type")
                .setQuery(queryBuilder)
                .get();
        // 获取查询结果
        SearchHits hits = response.getHits();
        System.out.println("查询记录条数:" + hits.getTotalHits());
        for (SearchHit hit : hits) {
    
    
            // 打印文档对象
            System.out.println(hit.getSourceAsString());
        }
    }

Query by Id

 @Test
public void testSearchById() throws Exception {
    
    
     // 创建一个查询对象,使用idsQuery(),addids中的参数可以动态选多个
     IdsQueryBuilder queryBuilder = QueryBuilders.idsQuery().addIds("1", "2", "3");
     search(queryBuilder);
 }

Query according to Term

@Test
public void testSearchByTerm() throws Exception {
    
    
    // 创建一个查询对象,使用termQuery
    // 参数1:要搜索的字段
    // 参数2:要搜索的关键词
    QueryBuilder queryBuilder = QueryBuilders.termQuery("title", "got");
    search(queryBuilder);
}

Match query based on string

 @Test
public void testStringQuery() throws Exception {
    
    
    // 创建一个查询对象
    // queryStringQuery:要匹配的字符串
    // defaultField:在哪一个字段下去匹配对应的字符串
    QueryBuilder queryBuilder = QueryBuilders.queryStringQuery("text")
            .defaultField("title");
    search(queryBuilder);
}

Highlight query results

 public void search(QueryBuilder queryBuilder, String highLightField) {
    
    
  // 创建Highlight对象
    HighlightBuilder highlightBuilder = new HighlightBuilder();
    // 设置需要高亮度显示的字段
    highlightBuilder.field(highLightField);
    // 设置样式的头
    highlightBuilder.preTags("<span style=\"color:red\">");
    // 设置样式的尾
    highlightBuilder.postTags("</span>");
    // 执行查询
    SearchResponse response = client.prepareSearch("cluster")
            .setTypes("test-type")
            .setQuery(queryBuilder)
            // 设置分页信息
            .setFrom(0)
            .setSize(3)
            .highlighter(highlightBuilder)
            .get();
    // 获取查询结果
    SearchHits hits = response.getHits();
    System.out.println("查询记录条数:" + hits.getTotalHits());
    for (SearchHit hit : hits) {
    
    
        // 打印文档对象
        System.out.println(hit.getSourceAsString());
        System.out.println("****************高亮结果******************");
        System.out.println(hit.getHighlightFields());
    }
}
@Test
public void testQueryhighLight() throws Exception {
    
    
     QueryBuilder queryBuilder = QueryBuilders.queryStringQuery("text")
             .defaultField("title");
     search(queryBuilder, "title");
}

Result: It is theoretically possible. It is only a problem of idea display. If it is placed on the page, the effect should be that the output field is red.
Insert picture description here

Paging query

Paging query only needs to add 2 parameters, which are added before client.get().
E.g:

SearchResponse response = client.prepareSearch("cluster")
                .setTypes("test-type")
                .setQuery(queryBuilder)
                // 设置分页信息
                .setFrom(0)
                .setSize(3)
                .get();

Guess you like

Origin blog.csdn.net/Zong_0915/article/details/107611039