ElasticSearch 实现分词全文检索 - Java SpringBoot ES 文档操作

目录

ElasticSearch 实现分词全文检索 - 概述
ElasticSearch 实现分词全文检索 - ES、Kibana、IK安装
ElasticSearch 实现分词全文检索 - Restful基本操作
ElasticSearch 实现分词全文检索 - Java SpringBoot ES 索引操作
ElasticSearch 实现分词全文检索 - Java SpringBoot ES 文档操作
ElasticSearch 实现分词全文检索 - 测试数据准备
ElasticSearch 实现分词全文检索 - term、terms查询
ElasticSearch 实现分词全文检索 - match、match_all、multimatch查询
ElasticSearch 实现分词全文检索 - id、ids、prefix、fuzzy、wildcard、range、regexp 查询
ElasticSearch 实现分词全文检索 - Scroll 深分页
ElasticSearch 实现分词全文检索 - delete-by-query
ElasticSearch 实现分词全文检索 - 复合查询
ElasticSearch 实现分词全文检索 - filter查询
ElasticSearch 实现分词全文检索 - 高亮查询
ElasticSearch 实现分词全文检索 - 聚合查询 cardinality
ElasticSearch 实现分词全文检索 - 经纬度查询
ElasticSearch 实现分词全文检索 - 搜素关键字自动补全(suggest)
ElasticSearch 实现分词全文检索 - SpringBoot 完整实现 Demo 附源码

Pom文件添加依赖包

<!-- https://mvnrepository.com/artifact/org.elasticsearch/elasticsearch -->
<dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>7.9.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.elasticsearch.client/elasticsearch-rest-high-level-client -->
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.9.3</version>
</dependency>
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.10</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.73</version>
</dependency>

创建索引

@Test
void createIndex() throws Exception{
    String indexName="person";
    RestHighLevelClient client = ESClient.getClient();
    //1. 准备索引的 settings
    Settings.Builder settings = Settings.builder()
            .put("number_of_shards", 3)
            .put("number_of_replicas", 1);

    //2. 准备索引的结构 Mappings
    XContentBuilder mappings = JsonXContent.contentBuilder()
            .startObject()
                .startObject("properties")
                    .startObject("name")
                        .field("type","text")
                    .endObject()
                    .startObject("age")
                        .field("type","integer")
                    .endObject()
                    .startObject("birthday")
                        .field("type","date")
                        .field("format","yyyy-MM-dd")
                    .endObject()
                .endObject()
            .endObject();

    //3. 将 Settings 和 Mappings 封装到一个Request 对象中
    CreateIndexRequest request = new CreateIndexRequest(indexName)
            .settings(settings)
            .mapping(mappings);

    //4. 通过 client 对象去连接ES并执行创建索引
    CreateIndexResponse resp = client.indices().create(request, RequestOptions.DEFAULT);

    //5. 输出
    System.out.println("resp:"+resp.toString());
}

Person 实体类

import com.fasterxml.jackson.annotation.JsonIgnore;

import java.util.Date;

public class Person {

    @JsonIgnore
    private  Integer id;

    private  String name;

    private  Integer age;

    private Date birthday;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
}

创建文档

@Test
void createDoc() throws Exception {
    String indexName = "person";
    RestHighLevelClient client = ESClient.getClient();
    //准备一个JSON数据
    Person person = new Person();
    person.setId(1);
    person.setName("张三");
    person.setAge(23);
    person.setBirthday(DateUtil.date());
    String personJson = JSON.toJSONStringWithDateFormat(person, "yyyy-MM-dd"); //FastJson 将日期格式化

    //准备一个Request对象
    IndexRequest request = new IndexRequest(indexName);
    request.id(person.getId().toString()); //手动指定ID
    request.source(personJson, XContentType.JSON);
    
    //通过 Client 对象执行添加
    IndexResponse resp = client.index(request, RequestOptions.DEFAULT);

    //输入结果
    System.out.println(resp.getResult().toString());
}

image

修改文档

@Test
void updateDoc() throws Exception {
    String indexName = "person";
    RestHighLevelClient client = ESClient.getClient();
    //创建一个MAP,指定需要修改的内容
    Map<String, Object> doc = new HashMap<>();
    doc.put("name", "张三丰");
    String docId = "1";
    //创建Request对象,封装数据
    UpdateRequest request = new UpdateRequest(indexName,docId);
    request.doc(doc);

    //通过client对象执行
    UpdateResponse update = client.update(request, RequestOptions.DEFAULT);

    //输入结果
    System.out.println(update.getResult().toString());
}

删除文档

@Test
void delete() throws Exception {

    String indexName = "person";
    RestHighLevelClient client = ESClient.getClient();

    //准备 request 对象
    DeleteRequest request = new DeleteRequest(indexName, "1");

    //通过client去操作
    DeleteResponse delete = client.delete(request, RequestOptions.DEFAULT);

    System.out.println("delete => " + delete);
}

批量添加

@Test
void batchCreateDoc() throws Exception {
    String indexName = "person";
    RestHighLevelClient client = ESClient.getClient();
    //准备一个JSON数据
    Person p1 = new Person();
    p1.setId(1);
    p1.setName("张三");
    p1.setAge(23);
    p1.setBirthday(DateUtil.date());
    String personJson1 = JSON.toJSONStringWithDateFormat(p1, "yyyy-MM-dd"); //FastJson 将日期格式化

    Person p2 = new Person();
    p2.setId(2);
    p2.setName("李四");
    p2.setAge(23);
    p2.setBirthday(DateUtil.date());
    String personJson2 = JSON.toJSONStringWithDateFormat(p2, "yyyy-MM-dd"); //FastJson 将日期格式化

    Person p3 = new Person();
    p3.setId(3);
    p3.setName("王五");
    p3.setAge(23);
    p3.setBirthday(DateUtil.date());
    String personJson3 = JSON.toJSONStringWithDateFormat(p3, "yyyy-MM-dd"); //FastJson 将日期格式化


    //准备一个Request对象
    BulkRequest bulkRequest = new BulkRequest();
    IndexRequest request1 = new IndexRequest(indexName)
            .id(p1.getId().toString()) //手动指定ID
            .source(personJson1, XContentType.JSON);

    IndexRequest request2 = new IndexRequest(indexName)
            .id(p2.getId().toString()) //手动指定ID
            .source(personJson2, XContentType.JSON);

    IndexRequest request3 = new IndexRequest(indexName)
            .id(p3.getId().toString()) //手动指定ID
            .source(personJson3, XContentType.JSON);

    bulkRequest.add(request1);
    bulkRequest.add(request2);
    bulkRequest.add(request3);

    //通过 Client 对象执行添加
    BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);

    //输入结果
    System.out.println(bulk.toString());
}

批量删除

@Test
void batchDelete() throws Exception {

    String indexName = "person";
    RestHighLevelClient client = ESClient.getClient();

    //准备 request 对象
    BulkRequest bulkRequest = new BulkRequest();
    bulkRequest.add(new DeleteRequest(indexName, "1"));
    bulkRequest.add(new DeleteRequest(indexName, "2"));

    //通过client去操作
    BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);

    System.out.println("delete => " + bulk.toString());
}
posted @ 2023-03-08 08:57  VipSoft  阅读(788)  评论(0编辑  收藏  举报