ElasticSearch的java客户端及SpringDataElasticSearch

文章目录

ElasticSearch第一章

一、java客户端的使用方法

​ 步骤:
​ 1、创建一个maven工程。
​ 2、添加jar包
​ 3、创建一个Settings对象,设置cluster.name属性
​ 4、创建一个TransportClient对象,基于Settings对象创建。PreBuiltTransportClient
​ 5、把服务端的节点的ip及端口号添加到TransportClient对象中。
​ 6、使用client对象实现索引的管理、文档的管理
​ 7、关闭client

二、索引库管理

1、创建索引库

  1.  //3、创建一个Settings对象,设置cluster.name属性
            Settings settings = Settings.builder()
                    .put("cluster.name", "my-elasticsearch")
                    .build();
    

1)、创建Client对象

  1. //	4、创建一个TransportClient对象,基于Settings对象创建。PreBuiltTransportClient
            TransportClient client = new PreBuiltTransportClient(settings);
            //	5、把服务端的节点的ip及端口号添加到TransportClient对象中。
            client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9301));
            client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9302));
            client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9303));
    

2)、使用client对象的方法创建索引库

  • client
        //代表是一个管理的动作
        .admin()
        //代表管理的是索引
        .indeces()
        //准备创建索引库
        .prepareCreate("索引库的名称")
        //执行操作
        .get();
    

2、设置mapping信息

1)创建索引库的时候设置mappings信息

1、创建一个client对象
2、XContentBuilder对象描述一个json数据
  • {
        "mappings":{
            "article":{
                "properties":{
                    "id":{
                        "type":"long",
                        "store":true
                    },
                    "title":{
                        "type":"text",
                        "store":"true",
                        "analyzer":"ik_max_word"
                    },
                    "content":{
                        "type":"text",
                        "store":"true",
                        "analyzer":"ik_max_word"
                    }
                }
            }
        }
    }
    
3、使用client创建索引库,设置mapping信息
4、关闭连接
5、代码演示(利用XContentBuilder来描述一个文档,直接拼接字符串也可)
  • @Test
        public void createIndexWithMapping() throws Exception {
            //1、创建一个client对象
            Settings settings = Settings.builder()
                    .put("cluster.name", "my-elasticsearch")
                    .build();
            TransportClient client = new PreBuiltTransportClient(settings)
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9301))
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9302))
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9303));
            //2、XContentBuilder对象描述一个json数据
            XContentBuilder builder = XContentFactory.jsonBuilder()
                    .startObject()
                        .startObject("mappings")
                            .startObject("article")
                                .startObject("properties")
                                    .startObject("id")
                                        .field("type","long")
                                        .field("store", true)
                                    .endObject()
                                    .startObject("title")
                                        .field("type", "text")
                                        .field("store", true)
                                        .field("analyzer", "ik_max_word")
                                    .endObject()
                                    .startObject("content")
                                        .field("type", "text")
                                        .field("store", true)
                                        .field("analyzer", "ik_max_word")
                                    .endObject()
                                .endObject()
                            .endObject()
                        .endObject()
                    .endObject();
            //3、使用client创建索引库,设置mapping信息
            client.admin()
                    .indices()
                    .prepareCreate("blog3")
                    //设置mappings信息
                    .setSource(builder)
                    .get();
            //4、关闭连接
            client.close();
        }
    

2)先创建索引库然后再设置mapping

1、url需要定位到type,给这个type设置mapping。

​ 请求体:

  • {
        "article":{
            "properties":{
                "id":{
                    "type":"long",
                    "store":true
                },
                "title":{
                    "type":"text",
                    "store":"true",
                    "analyzer":"ik_max_word"
                },
                "content":{
                    "type":"text",
                    "store":"true",
                    "analyzer":"ik_max_word"
                }
            }
        }
    }
    

    代码实现:

  • @Test
    public void putMapping() {
        //1、创建一个client对象
        //3、创建一个Settings对象,设置cluster.name属性
        Settings settings = Settings.builder()
            .put("cluster.name", "my-elasticsearch")
            .build();
        //	4、创建一个TransportClient对象,基于Settings对象创建。PreBuiltTransportClient
        TransportClient client = new PreBuiltTransportClient(settings);
        //	5、把服务端的节点的ip及端口号添加到TransportClient对象中。
        client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9301));
        client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9302));
        client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9303));
        //	6、使用client对象实现索引的管理、文档的管理
            //创建mapping的定义
            String mapping = "{\n" +
                    "\t\t\t\t\"article\":{\n" +
                    "\t\t\t\t\t\"properties\":{\n" +
                    "\t\t\t\t\t\t\"id\":{\n" +
                    "\t\t\t\t\t\t\t\"type\":\"long\",\n" +
                    "\t\t\t\t\t\t\t\"store\":true\n" +
                    "\t\t\t\t\t\t},\n" +
                    "\t\t\t\t\t\t\"title\":{\n" +
                    "\t\t\t\t\t\t\t\"type\":\"text\",\n" +
                    "\t\t\t\t\t\t\t\"store\":\"true\",\n" +
                    "\t\t\t\t\t\t\t\"analyzer\":\"ik_max_word\"\n" +
                    "\t\t\t\t\t\t},\n" +
                    "\t\t\t\t\t\t\"content\":{\n" +
                    "\t\t\t\t\t\t\t\"type\":\"text\",\n" +
                    "\t\t\t\t\t\t\t\"store\":\"true\",\n" +
                    "\t\t\t\t\t\t\t\"analyzer\":\"ik_max_word\"\n" +
                    "\t\t\t\t\t\t}\n" +
                    "\t\t\t\t\t}\n" +
                    "\t\t\t\t}\n" +
                    "\t\t\t}";
            //2、使用client设置mapping信息
            client.admin()
                    .indices()
                    //设置要设置mapping的索引库的名称
                    .preparePutMapping("blog")
                    //设置type的名称
                    .setType("article")
                    //type的定义
                    .setSource(mapping, XContentType.JSON)
                    //执行操作
                    .get();
            //3、关闭client
            client.close();
        }
    
2、步骤:

​ 1、创建一个client对象
​ 2、使用client设置mapping信息
​ preparePutMapping
​ 3、关闭client
​ mapping信息的定义可以使用XContentBuilder表示也可以直接拼接字符串。

3、删除索引库

​ 步骤:
​ 1)创建一个client对象
​ 2)使用client的方法删除索引库
​ prepareDelete
​ 参数就是索引库的名称
​ 3)关闭client

/*
* 删除索引库
*/
@Test
public void deleteIndex() {
     //3、创建一个Settings对象,设置cluster.name属性
        Settings settings = Settings.builder()
                .put("cluster.name", "my-elasticsearch")
                .build();
        //	4、创建一个TransportClient对象,基于Settings对象创建。PreBuiltTransportClient
        TransportClient client = new PreBuiltTransportClient(settings);
        //	5、把服务端的节点的ip及端口号添加到TransportClient对象中。
        client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9301));
        client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9302));
        client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9303));
        //	6、使用client对象实现索引的管理、文档的管理
    client.admin()
        .indices()
        //这里可以删除单个或多个,里面的参数是 (String... var1)
        .prepareDelete("blog2", "hello")
        .get();
     //	7、关闭client
        client.close();
}

三、文档的管理

  1. 设置一个公共init()初始化方法

    private TransportClient client;
    
    @Before
    public void init() throws Exception {
        //1、创建一个client对象
        Settings settings = Settings.builder()
            .put("cluster.name", "my-elasticsearch")
            .build();
        client = new PreBuiltTransportClient(settings)
            .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9301))
            .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9302))
            .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9303));
        }
    

1、文档的添加

​ 1)创建一个Client对象
​ 2)创建一个文档对象,XContentBuilder描述一个文档。

  • http://127.0.0.1/${端口号}/${索引库的名称}/${type类型的名称}/${文档的id}
    json数据:
    {
    	"id":1,
    	"title":"内蒙古自治区卫生健康委关于取消2020年春节放假的紧急通知",
    	"content":"鉴于当前新型冠状病毒感染的肺炎疫情的严峻形势,根据国家和自治区工作部署,自治区		卫生健康委党组决定,全区各级卫生行政部门、各级各类公立医疗卫生机构,立即取消春节放假,从	  2020年1月26日开始正常上班,严格执行上下班制度"
    }
    

​ 3)使用client把文档对象写入索引库。
​ 4)关闭client

​ 5)代码实现:

  • @Test
    public void addDocument() throws Exception {
        //1)创建一个Client对象
        //2)创建一个文档对象,XContentBuilder描述一个文档。
        XContentBuilder builder = XContentFactory.jsonBuilder()
            .startObject()
            .field("id", 1)
            .field("title", "一篇自媒体文章就让百度股价跌6%?别逗了")
            .field("content", "测试文档的内容")
            .endObject();
        //3)使用client把文档对象写入索引库。
        client.prepareIndex("blog", "article", "1")
            //设置文档信息
            .setSource(builder)
            //执行操作
            .get();
        //4)关闭client
        client.close();
    }
    

2、添加文档的第二种方法

​ 可以使用一个pojo对象表示文档。
​ 需要把pojo对象转换成json数据。
​ fastJson
​ Jackson

​ 文档对象可以使用XContentBuilder表示也可以使用pojo对象表示,
​ 使用pojo对象需要使用工具包把pojo转换成json。

​ 实体类对象:

  • public class Article {
        private long id;
        private String title;
        private String content;
        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;}
    }
    
  • 添加文档实例2:

    @Test
    public void addDocument2() throws Exception {
        //创建一个文档对象
        Article article = new Article();
        article.setId(2);
        article.setTitle("达沃斯论坛大幕拉开,重要议题看这里!");
        article.setContent("“雪龙”船碰撞冰山,南极科考有多难?比月球了解少");
        //把article对象转换成json
        ObjectMapper objectMapper = new ObjectMapper();
        String doc = objectMapper.writeValueAsString(article);
        System.out.println(doc);
        //使用client把文档写入索引库
        client.prepareIndex()
            //索引库的名称
            .setIndex("blog")
            //type的名称
            .setType("article")
            //文档的id
            .setId("2")
            //设置文档对象
            .setSource(doc, XContentType.JSON)
            .get();
        client.close();
    }
    

3、修改文档

​ 可以直接使用添加文档的方法实现修改。
​ es的api中有更新文档的方法
​ prepareUpdate方法

  • 修改文档实例2:

    @Test
    public void updateDocument() throws Exception {
        //创建一个文档对象
        Article article = new Article();
        article.setId(1);
        article.setTitle("落马8天后,赵正永首次被官方定性!");
        article.setContent("想坐收中美摩擦“渔翁之利”?这个国家想的有点多");
        //把article对象转成json
        String doc = new ObjectMapper().writeValueAsString(article);
        //更新文档
        client.prepareUpdate("blog", "article", "1")
            .setDoc(doc, XContentType.JSON)
            .get();
        client.close();
    }
    

4、删除文档

​ 根据id删除文档
​ 使用client对象的prepareDelete方法实现删除。

  • 删除文档实例:

    @Test
    public void deleteDocument() throws Exception {
        client.prepareDelete("blog", "article", "2").get();
    }
    

四、文档的查询

步骤:初始化方法

  • private TransportClient client;
    @Before
    public void init() throws Exception {
        //1、创建一个client对象
        Settings settings = Settings.builder()
            .put("cluster.name", "my-elasticsearch")
            .build();
        client = new PreBuiltTransportClient(settings)
            .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9301))
            .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9302))
            .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9303));
    }
    

1)创建一个client对象

2)创建一个QueryBuilder对象,查询条件。使用QueryBuilders工具类创建。

3)使用client对象执行查询

​ 设置查询的索引库、type、查询条件

4)执行查询,并返回查询结果。QueryResponse对象。

5)从QueryResponse对象中取查询结果。

6)取查询结果的总记录数。

8)取查询结果列表

1、根据id查询

​ QueryBuilders.idsQuery().setIds(“查询的id”)

  • 代码实现:

    @Test
    public void findById() throws Exception {
        //1)创建一个client对象
        //2)创建一个QueryBuilder对象,查询条件。使用QueryBuilders工具类创建。
        QueryBuilder queryBuilder = QueryBuilders.idsQuery().addIds("1");
        //3)使用client对象执行查询
        //设置查询的索引库
        //设置查询的索引库、type、查询条件
        SearchResponse response = client.prepareSearch("blog")
            //设置查询的type
            .setTypes("article")
            //设置查询条件
            .setQuery(queryBuilder)
            //执行查询
            .get();
        //4)执行查询,并返回查询结果。QueryResponse对象。
        //5)从QueryResponse对象中取查询结果。
        SearchHits searchHits = response.getHits();
        //6)取查询结果的总记录数。
        long totalHits = searchHits.getTotalHits();
        System.out.println("查询结果总记录数:" + totalHits);
        //8)取查询结果列表
        SearchHit[] hits = searchHits.getHits();
        for (SearchHit hit : hits) {
            //文档对象使用map表示
            Map<String, Object> source = hit.getSource();
            System.out.println(source);
        }
    }
    

2、根据term查询

​ 关键词,term包含两部分内容:
​ 关键字所在的字段
​ 关键词本身。
​ 关键词必须是关键词列表中存在的关键词,否则就没有结果。
​ QueryBuilders.termQuery(“title”, “落马”)
​ 查询默认进行分页处理,每页默认显示10条数据。

  • 代码实现:

    @Test
    public void findByTerm() {
        //创建查询条件
        QueryBuilder queryBuilder = QueryBuilders.termQuery("content", "南极");
        //执行查询
        SearchResponse response = client.prepareSearch("blog")
            .setTypes("article")
            .setQuery(queryBuilder)
            .get();
        SearchHits searchHits = response.getHits();
        System.out.println("总记录数:" + searchHits.getTotalHits());
        Iterator<SearchHit> iterator = searchHits.iterator();
        while(iterator.hasNext()) {
            SearchHit hit = iterator.next();
            Map<String, Object> source = hit.getSource();
            System.out.println(source);
        }
    }
    

3、根据query_string查询

​ 先对查询的内容分词,然后基于分词之后的结果进行查询。
​ QueryBuilders.queryStringQuery(“查询条件”).defaultField(“title”)

  • 代码实现

    @Test
    public void findByQueryString() {
        //创建查询条件
        QueryBuilder queryBuilder = QueryBuilders.queryStringQuery("雪龙的伤害有多大").defaultField("content");
        //执行查询
        SearchResponse response = client.prepareSearch("blog")
            .setTypes("article")
            .setQuery(queryBuilder)
            .get();
        SearchHits searchHits = response.getHits();
        System.out.println("总记录数:" + searchHits.getTotalHits());
        SearchHit[] hits = searchHits.getHits();
        for (SearchHit hit : hits) {
            System.out.println(hit.getSource());
        }
    
    }
    

4、查询带分页

​ 设置分页信息,需要设置两个参数:
​ from:起始的行号。默认从0开始。
​ size:每页显示的行数,默认是10
​ 两者类似于mysql里面的 limit
​ 在client对象中设置。

  • 代码实现:

    //创建查询条件
        QueryBuilder queryBuilder = QueryBuilders.queryStringQuery("雪龙的伤害有多大").defaultField("content"); 
    SearchResponse response = client.prepareSearch("blog")
            .setTypes("article")
            .setQuery(queryBuilder)
    		//设置分分页信息
            .setFrom(5)//起始的行号从第5条数据查询,每页查询5条,相当于现在取的是第二页
            .setSize(5)
       	.get();
    

5、高亮显示

​ 在关键词前后分别添加前缀和后缀。

1)执行查询之前需要设置高亮的条件

​ 1、高亮显示的字段
​ 2、高亮显示的前缀
​ 3、高亮显示的后缀

2)执行查询
3)取高亮结果

​ 高亮结果不会在查询结果的文档中反映出来。
​ 需要单独取高亮结果。从SearchHit对象中取高亮结果。

4) 代码实现:
@Test
public void findByHighlighting() {
    //查询条件
    QueryBuilder queryBuilder = QueryBuilders.termQuery("content", "雪龙");
    //查询之前先设置高亮信息
    HighlightBuilder highlightBuilder = new HighlightBuilder()
        //设置高亮显示的字段
        .field("content")
        //设置高亮显示的前缀
        .preTags("<em>")
        //设置高亮显示的后缀
        .postTags("</em>");
    //执行查询
    SearchResponse response = client.prepareSearch("blog")
        .setTypes("article")
        //查询条件
        .setQuery(queryBuilder)
        //高亮条件
        .highlighter(highlightBuilder)
        .get();
    //取查询结果
    SearchHits searchHits = response.getHits();
    //总记录数
    long totalHits = searchHits.getTotalHits();
    System.out.println("总记录数:" + totalHits);
    //取结果列表
    SearchHit[] hits = searchHits.getHits();
    for (SearchHit hit : hits) {
        Map<String, Object> doc = hit.getSource();
        System.out.println(doc);
        //取高亮的结果
        Map<String, HighlightField> highlightFields = hit.getHighlightFields();
        //根据高亮字段取高亮结果
        HighlightField highlightField = highlightFields.get("content");
        //高亮的结果,一般情况下只有一个值。
        Text[] fragments = highlightField.getFragments();
        Text fragment = fragments[0];
        //最终的高亮结果
        String hlContent = fragment.string();
        System.out.println(hlContent);

    }
}

五、SpringDataElasticSearch

​ 和SpringDataJpa同属一个项目。使用方法基本相同。

1、使用方法

1)把SpringDataElasticSearch整合Spring

1、创建一个TransportClient对象,在容器中单例。
2、创建一个ElasticSearchTemplate模板对象。
3、Dao的包扫描器。
4、配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:elasticsearch="http://www.springframework.org/schema/data/elasticsearch"
       xsi:schemaLocation="
      http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context.xsd
      http://www.springframework.org/schema/data/elasticsearch
      http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch-1.0.xsd">
    <!--配置TransportClient对象-->
    <elasticsearch:transport-client id="client"
                                    cluster-name="my-elasticsearch"
                                    cluster-nodes="127.0.0.1:9301,127.0.0.1:9302,127.0.0.1:9303"/>

    <!--配置ElasticSearchTemplate对象-->
    <bean id="template" class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate">
        <constructor-arg name="client" ref="client"/>
    </bean>

    <!--配置dao的包扫描器-->
    <elasticsearch:repositories base-package="com.itheima.es.dao"
                                elasticsearch-template-ref="template"/>
</beans>

2)创建实体类。配置映射关系。

​ 对应索引库中的type配置映射关系。
​ @Document: 配置实体类和索引库中的type的映射关系
​ indexName:索引库的名称
​ type:索引库中type的名称
​ @Id:标注id属性
​ @Field:配置字段的属性
​ type:字段的数据类型
​ store:是否存储,默认是false
​ index:是否索引,默认是true
​ analyzer:配置分词器

  • 实体类对象:

    import org.springframework.data.annotation.Id;
    import org.springframework.data.elasticsearch.annotations.Document;
    import org.springframework.data.elasticsearch.annotations.Field;
    import org.springframework.data.elasticsearch.annotations.FieldType;
    
    /**
     * @Document: 配置实体类和索引库中的type的映射关系
     *  indexName:索引库的名称
     *  type:索引库中type的名称
     */
    @Document(indexName = "blog2", type = "article")
    public class Article {
        @Id
        @Field(type = FieldType.Long, store = true)
        private long id;
        @Field(type = FieldType.text, store = true, analyzer = "ik_max_word")
        private String title;
        @Field(type = FieldType.text, store = true, analyzer = "ik_max_word")
        private String content;
        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;}
        @Override
        public String toString() {
            return "Article{" +
                    "id=" + id +
                    ", title='" + title + '\'' +
                    ", content='" + content + '\'' +
                    '}';
        }
    }
    

3)dao。创建一个接口,需要继承ElasticSearchRepository接口。

  • 代码实现:

    import com.itheima.es.entity.Article;
    import org.springframework.data.domain.Page;
    import org.springframework.data.domain.Pageable;
    import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
    import java.util.List;
    
    public interface ArticleDao extends ElasticsearchRepository<Article, Long> {
        List<Article> findByTitle1(String title);
        Page<Article> findByTitle2(String title, Pageable pageable);
    }
    

2、索引库的管理

​ 都需要使用ElasticSearchTemplate对象

1)创建索引库

​ createIndex方法
​ 参数类型:
​ 可以指定索引库的名称,只会创建一个索引库,没有mapping信息。

  • @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration("classpath:applicationContext.xml")
    public class SpringDataESTest {
        @Autowired
        private ElasticsearchTemplate template;
        @Test
        public void createIndex() {
            template.createIndex("hello");
        }
    }
    

​ 也可以使用实体类类型,创建索引库同时这种mapping信息。

  • @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration("classpath:applicationContext.xml")
    public class SpringDataESTest {
        @Autowired
        private ElasticsearchTemplate template;
        @Autowired
        private ArticleDao articleDao;
        @Test
        public void createIndex() {
            template.createIndex(Article.class);
        }
    }
    

2)设置mapping

​ putMaping方法,需要实体类作为参数

  • @Test
    public void putMaping() {
        template.putMapping(Article.class);
    }
    

3)删除索引

​ deleteIndex

  • @Test
    public void deleteIndex() {
        template.deleteIndex("hello");
    }
    

3、管理文档

​ 直接使用dao对象的方法实现增删改查。

1)添加文档

​ 使用save方法保存文档

  • @Test
    public void addDocument() {
        for (int i = 0; i < 100; i++) {
            //创建Article对象
            Article article = new Article();
            article.setId(i);
            article.setTitle("Lucene介绍与入门使用 - 高压锅里的小白" + i);
            article.setContent("apache软件基金会4 jakarta项目组的一个子项目,是一" + i);
            //保存到ES
            articleDao.save(article);
        }
    }
    

2)修改文档

​ 和添加文档使用的是同一个方法。
​ save

  • @Test
    public void addDocument() {
        //创建Article对象
        Article article = new Article();
        article.setId(1);
        article.setTitle("Lucene介绍与入门使用 - 高压锅里的小白");
        article.setContent("apache软件基金会4 jakarta项目组的一个子项目,是一");
        //保存到ES
        articleDao.save(article);
    }
    

3)删除文档

​ deleteById

  • @Test
    public void deleteDocument() {
        articleDao.deleteById(1L);
    }
    

4、查询文档

1)根据id查询

​ 可以直接使用dao的findById方法查询,Optional是jdk1.8的新类,用来解决空指针异常的问题

  • @Test
    public void findById() {
        Optional<Article> optional = articleDao.findById(1l);
        if (optional.isPresent()) {//isPresent()判断值存在返回true
            Article article = optional.get();//调用get()会返回该对象
            System.out.println(article);
        }
    }
    

2)findAll

​ 查询全部
​ 默认是不分页。

  • @Test
    public void findAll() {
        Iterable<Article> iterable = articleDao.findAll();
        for (Article article : iterable) {
            System.out.println(article);
        }
    }
    

​ 如果想实现分页的话应该使用Pageable参数。
​ 返回值就是Page对象:
​ 总记录数可以使用
​ 总页数不对

  • @Test
    public void findAll() {
        Page<Article> page = articleDao.findAll(PageRequest.of(0, 5));
        long totalElements = page.getTotalElements();
        System.out.println(totalElements);
        int totalPages = page.getTotalPages();
        //取结果列表
        List<Article> content = page.getContent();
        System.out.println(totalPages);
        for (Article article : content) {
            System.out.println(article);
        }
    }
    

3)使用方法命名规则查询

​ 相当于term查询方式。
​ 默认是分页的,每页显示10条数据。

  • @Test
    public void testfindByTitle() {
        List<Article> list = articleDao.findByTitle1("Lucene");
        for (Article article : list) {
            System.out.println(article);
        }
    }
    

​ 如果自定义分页,应该使用Pageable参数。
​ 类似于模糊查询,类似于sql中的like

  • @Test
    public void testfindByTitle() {
        Page<Article> page = articleDao.findByTitle2("Lucene介绍与入门使用", PageRequest.of(0, 5));
        long totalElements = page.getTotalElements();
        System.out.println(totalElements);
        int totalPages = page.getTotalPages();
        System.out.println(totalPages);
        List<Article> content = page.getContent();
        for (Article article : content) {
            System.out.println(article);
        }
    }
    

4)使用QueryString查询

​ dao中没有对应的方法。
​ 需要使用NativeSearchQuery对象创建查询条件。
​ 使用Template对象执行查询。

  • @Test
    public void testQueryStringQuery() {
        //创建一个查询条件
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
            .withQuery(QueryBuilders.queryStringQuery("lucene是一个全文检索api"))
            //设置分页条件
            .withPageable(PageRequest.of(0, 20))
            .build();
        //使用Template对象执行查询
        List<Article> articles = template.queryForList(searchQuery, Article.class);
        for (Article article : articles) {
            System.out.println(article);
        }
    }
    
发布了63 篇原创文章 · 获赞 2 · 访问量 3166

猜你喜欢

转载自blog.csdn.net/qq_41821006/article/details/104430288