1.创建一个maven工程

my-es

pom

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.elasticsearch</groupId>
  4. <artifactId>elasticsearch</artifactId>
  5. <version>5.6.8</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>org.elasticsearch.client</groupId>
  9. <artifactId>transport</artifactId>
  10. <version>5.6.8</version>
  11. </dependency>
  12. <dependency>
  13. <groupId>junit</groupId>
  14. <artifactId>junit</artifactId>
  15. <version>4.12</version>
  16. </dependency>
  17. <dependency>
  18. <groupId>org.springframework.data</groupId>
  19. <artifactId>spring-data-elasticsearch</artifactId>
  20. <version>3.0.5.RELEASE</version>
  21. </dependency>
  22. <dependency>
  23. <groupId>org.springframework</groupId>
  24. <artifactId>spring-test</artifactId>
  25. <version>5.0.4.RELEASE</version>
  26. </dependency>
  27. </dependencies>

2.编写applicationConetext.xml配置

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:elasticsearch="http://www.springframework.org/schema/data/elasticsearch"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans.xsd
  8. http://www.springframework.org/schema/context
  9. http://www.springframework.org/schema/context/spring-context.xsd
  10. http://www.springframework.org/schema/data/elasticsearch
  11. http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch-1.0.xsd">
  12. <!-- 扫描Dao包,自动创建实例 -->
  13. <elasticsearch:repositories base-package="com.hikktn.dao"/>
  14. <!-- 扫描Service包,创建Service的实体 -->
  15. <context:component-scan base-package="com.hikktn.service"/>
  16. <!-- 配置elasticSearch的连接 -->
  17. <elasticsearch:transport-client id="client" cluster-nodes="localhost:9300" cluster-name="my-application"/>
  18. <!-- spring data elasticSearcheDao 必须继承 ElasticsearchTemplate -->
  19. <bean id="elasticsearchTemplate"
  20. class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate">
  21. <constructor-arg name="client" ref="client"/>
  22. </bean>
  23. </beans>

如果设置cluster-name配置,那么需要开启elasticsearch.yml的配置

  1. # ======================== Elasticsearch Configuration =========================
  2. #
  3. # NOTE: Elasticsearch comes with reasonable defaults for most settings.
  4. # Before you set out to tweak and tune the configuration, make sure you
  5. # understand what are you trying to accomplish and the consequences.
  6. #
  7. # The primary way of configuring a node is via this file. This template lists
  8. # the most important settings you may want to configure for a production cluster.
  9. #
  10. # Please consult the documentation for further information on configuration options:
  11. # https://www.elastic.co/guide/en/elasticsearch/reference/index.html
  12. #
  13. # ---------------------------------- Cluster -----------------------------------
  14. #
  15. # Use a descriptive name for your cluster:
  16. #
  17. cluster.name: my-application
  18. #
  19. # ------------------------------------ Node ------------------------------------
  20. #
  21. # Use a descriptive name for the node:
  22. #
  23. node.name: node-1
  24. #
  25. # Add custom attributes to the node:
  26. #
  27. #node.attr.rack: r1
  28. #
  29. # ----------------------------------- Paths ------------------------------------
  30. #
  31. # Path to directory where to store the data (separate multiple locations by comma):
  32. #
  33. #path.data: /path/to/data
  34. #
  35. # Path to log files:
  36. #
  37. #path.logs: /path/to/logs
  38. #
  39. # ----------------------------------- Memory -----------------------------------
  40. #
  41. # Lock the memory on startup:
  42. #
  43. #bootstrap.memory_lock: true
  44. #
  45. # Make sure that the heap size is set to about half the memory available
  46. # on the system and that the owner of the process is allowed to use this
  47. # limit.
  48. #
  49. # Elasticsearch performs poorly when the system is swapping the memory.
  50. #
  51. # ---------------------------------- Network -----------------------------------
  52. #
  53. # Set the bind address to a specific IP (IPv4 or IPv6):
  54. #
  55. #network.host: 192.168.0.1
  56. #
  57. # Set a custom port for HTTP:
  58. #
  59. #http.port: 9200
  60. #
  61. # For more information, consult the network module documentation.
  62. #
  63. # --------------------------------- Discovery ----------------------------------
  64. #
  65. # Pass an initial list of hosts to perform discovery when new node is started:
  66. # The default list of hosts is ["127.0.0.1", "[::1]"]
  67. #
  68. #discovery.zen.ping.unicast.hosts: ["host1", "host2"]
  69. discovery.zen.ping.unicast.hosts: ["127.0.0.1"]
  70. client.transport.ping_timeout: 60s
  71. #
  72. # Prevent the "split brain" by configuring the majority of nodes (total number of master-eligible nodes / 2 + 1):
  73. #
  74. #discovery.zen.minimum_master_nodes: 3
  75. #
  76. # For more information, consult the zen discovery module documentation.
  77. #
  78. # ---------------------------------- Gateway -----------------------------------
  79. #
  80. # Block initial recovery after a full cluster restart until N nodes are started:
  81. #
  82. #gateway.recover_after_nodes: 3
  83. #
  84. # For more information, consult the gateway module documentation.
  85. #
  86. # ---------------------------------- Various -----------------------------------
  87. #
  88. # Require explicit names when deleting indices:
  89. #
  90. #action.destructive_requires_name: true
  91. http.cors.enabled: true
  92. http.cors.allow-origin: "*"
  93. network.host: 127.0.0.1

3.编写pojo实体类

注解解释:

@Document :文档对象

  • indexName:索引名称
  • type:索引类型
  • shards:分片数量,默认5
  • replicas:副本数量,默认1

@Feild:成员变量

  • type:字段类型
  • index:是否索引,默认为true
  • store:是否存储,默认false
  • analyzer:分词器
  • searchAnalyzer:备用分词器
  1. package com.hikktn.pojo;
  2. import org.springframework.data.annotation.Id;
  3. import org.springframework.data.elasticsearch.annotations.Document;
  4. import org.springframework.data.elasticsearch.annotations.Field;
  5. import org.springframework.data.elasticsearch.annotations.FieldType;
  6. /**
  7. * @ClassName Item
  8. * @Description TODO
  9. * @Author lisonglin
  10. * @Date 2021/5/7 16:37
  11. * @Version 1.0
  12. */
  13. @Document(indexName = "item", type = "item")
  14. public class Item {
  15. @Id
  16. @Field(index = true, store = true, type = FieldType.Integer)
  17. private Integer id;
  18. @Field(index = true, store = true, analyzer = "ik_smart", searchAnalyzer = "ik_smart", type = FieldType.text)
  19. private String title;
  20. @Field(index = true, store = true, analyzer = "ik_smart", searchAnalyzer = "ik_smart", type = FieldType.text)
  21. private String content;
  22. public Integer getId() {
  23. return id;
  24. }
  25. public void setId(Integer id) {
  26. this.id = id;
  27. }
  28. public String getTitle() {
  29. return title;
  30. }
  31. public void setTitle(String title) {
  32. this.title = title;
  33. }
  34. public String getContent() {
  35. return content;
  36. }
  37. public void setContent(String content) {
  38. this.content = content;
  39. }
  40. public Item(Integer id, String title, String content) {
  41. this.id = id;
  42. this.title = title;
  43. this.content = content;
  44. }
  45. public Item() {
  46. }
  47. @Override
  48. public String toString() {
  49. return "Item{" + "id=" + id + ", title='" + title + '\'' + ", content='" + content + '\'' + '}';
  50. }
  51. }

3.编写dao

  1. package com.hikktn.dao;
  2. import com.hikktn.pojo.Item;
  3. import org.springframework.data.domain.Page;
  4. import org.springframework.data.domain.Pageable;
  5. import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
  6. import java.util.List;
  7. /**
  8. * @ClassName ItemRepository
  9. * @Description TODO
  10. * @Author lisonglin
  11. * @Date 2021/5/7 16:40
  12. * @Version 1.0
  13. */
  14. public interface ItemRepository extends ElasticsearchRepository<Item, Integer> {
  15. List<Item> findByTitleAndContent(String title, String content);
  16. Page<Item> findByTitleOrContent(String title, String content, Pageable pageable);
  17. Page<Item> findByTitleAndContentAndIdBetween(String title, String content, int min, int max, Pageable pageable);
  18. }

4.编写service

  1. package com.hikktn.service;
  2. import com.hikktn.pojo.Item;
  3. import java.util.List;
  4. /**
  5. * @ClassName ItemService
  6. * @Description TODO
  7. * @Author lisonglin
  8. * @Date 2021/5/7 16:41
  9. * @Version 1.0
  10. */
  11. public interface ItemService {
  12. }

5.编写service.impl

  1. package com.hikktn.service.impl;
  2. import com.hikktn.dao.ItemRepository;
  3. import com.hikktn.pojo.Item;
  4. import com.hikktn.service.ItemService;
  5. /**
  6. * @ClassName ItemServiceImpl
  7. * @Description TODO
  8. * @Author lisonglin
  9. * @Date 2021/5/7 16:41
  10. * @Version 1.0
  11. */
  12. @Service
  13. public class ItemServiceImpl implements ItemService {
  14. }

6.ElasticSearch 基本使用CRUD

  1. public interface ItemService {
  2. /**
  3. * 新增
  4. *
  5. * @param item
  6. */
  7. void save(Item item);
  8. /**
  9. * 删除
  10. *
  11. * @param item
  12. */
  13. void delete(Item item);
  14. /**
  15. * 批量保存
  16. *
  17. * @param list
  18. */
  19. void saveAll(List<Item> list);
  20. /**
  21. * 查询所有数据
  22. *
  23. * @return
  24. */
  25. public Iterable<Item> findAll();
  26. }
  1. @Service
  2. public class ItemServiceImpl implements ItemService {
  3. @Autowired
  4. private ItemRepository itemRepository;
  5. public void save(Item item) {
  6. this.itemRepository.save(item);
  7. }
  8. public void delete(Item item) {
  9. this.itemRepository.delete(item);
  10. }
  11. public void saveAll(List<Item> list) {
  12. this.itemRepository.saveAll(list);
  13. }
  14. public Iterable<Item> findAll() {
  15. Iterable<Item> items = this.itemRepository.findAll();
  16. return items;
  17. }
  18. }

elasticsearchTemplate 是已经封装好的各种方法,不需要程序员很麻烦的写方法调用。

  1. @RunWith(SpringJUnit4ClassRunner.class)
  2. @ContextConfiguration(locations = "classpath:applicationContext.xml")
  3. public class SpringDataESTest {
  4. @Autowired
  5. private ItemService itemService;
  6. @Autowired
  7. private ElasticsearchTemplate elasticsearchTemplate;
  8. /**
  9. * 添加索引,并添加映射
  10. */
  11. @Test
  12. public void createIndex() {
  13. this.elasticsearchTemplate.createIndex(Item.class);
  14. this.elasticsearchTemplate.putMapping(Item.class);
  15. }
  16. /**
  17. * 添加文档
  18. *
  19. */
  20. @Test
  21. public void testSave() {
  22. Item item = new Item();
  23. item.setId(100);
  24. item.setTitle("SpringData ES");
  25. item.setContent("今天我们使用SpringData ES完成搜索功能。");
  26. this.itemService.save(item);
  27. }
  28. /**
  29. * 修改,和新增的代码是一样的,如果id存在就是修改,如果id不存在就是新增
  30. *
  31. */
  32. @Test
  33. public void testUpdate() {
  34. Item item = new Item();
  35. item.setId(100);
  36. item.setTitle("SpringData ES");
  37. item.setContent("今天我们使用SpringData ES完成job搜索功能。");
  38. this.itemService.save(item);
  39. }
  40. /**
  41. * 删除索引
  42. */
  43. @Test
  44. public void testDelete() {
  45. Item item = new Item();
  46. item.setId(100);
  47. this.itemService.delete(item);
  48. }
  49. /**
  50. * 查询索引
  51. */
  52. @Test
  53. public void testFindAll() {
  54. Iterable<Item> items = this.itemService.findAll();
  55. for (Item item : items) {
  56. System.out.println(item);
  57. }
  58. }
  59. }

测试

6.1 测试创建索引

执行方法

验证

Spring Data ElasticSearch 常用API调用 - 图1

Spring Data ElasticSearch 常用API调用 - 图2

Spring Data ElasticSearch 常用API调用 - 图3

6.2 测试添加索引

Spring Data ElasticSearch 常用API调用 - 图4

6.3 测试查询索引

Spring Data ElasticSearch 常用API调用 - 图5

6.4 测试修改索引

Spring Data ElasticSearch 常用API调用 - 图6

Spring Data ElasticSearch 常用API调用 - 图7

6.5 测试删除索引

只是将里面的文档删除,索引依然存在

Spring Data ElasticSearch 常用API调用 - 图8

Spring Data ElasticSearch 常用API调用 - 图9

7.批量添加索引

  1. public interface ItemService {
  2. /**
  3. * 查询所有数据
  4. *
  5. * @return
  6. */
  7. public Iterable<Item> findAll();
  8. }
  1. @Service
  2. public class ItemServiceImpl implements ItemService {
  3. @Autowired
  4. private ItemRepository itemRepository;
  5. public Iterable<Item> findAll() {
  6. Iterable<Item> items = this.itemRepository.findAll();
  7. return items;
  8. }
  9. }
  1. @Autowired
  2. private ItemService itemService;
  3. // 批量保存
  4. @Test
  5. public void testSaveAll() {
  6. //创建集合
  7. List<Item> list = new ArrayList<Item>();
  8. //封装数据
  9. for (int i = 1; i < 10; i++) {
  10. Item item = new Item();
  11. item.setId(i);
  12. item.setTitle("SpringData ES " + i);
  13. item.setContent("今天我们使用SpringData ES完成job搜索功能。" + i);
  14. list.add(item);
  15. }
  16. //批量保存
  17. this.itemService.saveAll(list);
  18. }

Spring Data ElasticSearch 常用API调用 - 图10

8.查询全部索引

  1. public interface ItemService {
  2. /**
  3. * 查询所有数据
  4. *
  5. * @return
  6. */
  7. public Iterable<Item> findAll();
  8. }
  1. public class ItemServiceImpl implements ItemService {
  2. @Autowired
  3. private ItemRepository itemRepository;
  4. public Iterable<Item> findAll( String properties) {
  5. return this.itemRepository.findAll(Sort.by(Sort.Direction.DESC,properties));
  6. }
  7. }
  1. //查询所有数据
  2. @Test
  3. public void testFindAll() {
  4. Iterable<Item> items = this.itemService.findAll();
  5. for (Item item : items) {
  6. System.out.println(item);
  7. }
  8. }

Spring Data ElasticSearch 常用API调用 - 图11

9.查询全部索引,按照id倒序

  1. public interface ItemService {
  2. /**
  3. * 排序查询
  4. * @param properties
  5. * @return
  6. */
  7. public Iterable<Item> findAll(String properties);
  8. }
  1. @Service
  2. public class ItemServiceImpl implements ItemService {
  3. @Autowired
  4. private ItemRepository itemRepository;
  5. public Iterable<Item> findAll( String properties) {
  6. return this.itemRepository.findAll(Sort.by(Sort.Direction.DESC,properties));
  7. }
  8. }

该方法需要

  1. // 根据id倒序
  2. @Test
  3. public void testFindAllDesc() {
  4. Iterable<Item> items = this.itemService.findAll("title");
  5. for (Item item : items) {
  6. System.out.println(item);
  7. }
  8. }

Spring Data ElasticSearch 常用API调用 - 图12

10.自定义方法查询

不可以编写一个没有属性的方法,否则会报找不到的异常

关键字 命名规则 解释 实例
and findByField1AndField2 根据Field1和Field2获得数据 findByTitleAndContent
or findByField1OrField2 根据Field1或Field2获得数据 findByTitleOrContent
is findByField 根据Field获得数据 findByTitle
not findByFieldNot 根据Field获得补集数据 findByTitleNot
between findByFieldBetween 获得指定范围的数据 findByPriceBetween
lessThanEqual findByFieldLessThan 获得小于等于指定值的数据 findByPriceLessThan
GreaterThanEqual findByFieldGreaterThan 获取大于等于指定值的数据 findByPriceGreaterThan
Before findByFieldBefore 获得小于等于指定值的数据 findByPriceBefore
After findByFieldAfter 获取大于等于指定值的数据 findByPriceAfter
Like findByFieldLike 条件查询 findByNameLike
StartingWith findByFieldStartingWith 首字符查询 findByNameStartingWith
EndingWith findByFieldEndingWith 末尾字符查询 findByNameEndingWith
Contains/Containing findByFieldContaining 模糊查询 findByNameContaining
In findByFieldIn(Collectionnames) 多条件 查询 findByNameIn(Collectionnames)
NotIn findByFieldNotIn(Collectionnames) 多条件不成立查询 findByNameNotIn(Collectionnames)
Near findByFieldNear 是否存在 findByStoreNear
True findByFieldTrue 获取Field为true的数据 findByAvailableTrue
False findByFieldFalse 获取Field为false的数据 findByAvailableFalse
OrderBy findByFieldTrueOrderByFieldDesc 获取倒序的数据 findByAvailableTrueOrderByNameDesc
  1. public interface ItemRepository extends ElasticsearchRepository<Item, Integer> {
  2. List<Item> findByTitleAndContent(String title, String content);
  3. Page<Item> findByTitleOrContent(String title, String content, Pageable pageable);
  4. Page<Item> findByTitleAndContentAndIdBetween(String title, String content, int min, int max, Pageable pageable);
  5. }
  1. public interface ItemService {
  2. /**
  3. * 分页查询
  4. *
  5. * @param page
  6. * @param rows
  7. * @return
  8. */
  9. Page<Item> findByPage(int page, int rows);
  10. /**
  11. * 根据标题和内容查询,交集
  12. *
  13. * @param title
  14. * @param content
  15. * @return
  16. */
  17. List<Item> findByTitleAndContent(String title, String content);
  18. /**
  19. * 根据标题或内容分页查询,并集
  20. *
  21. * @param title
  22. * @param content
  23. * @param page
  24. * @param rows
  25. * @return
  26. */
  27. Page<Item> findByTitleOrContent(String title, String content, Integer page, Integer rows);
  28. /**
  29. * 根据Title或者Content和Id的范围,进行分页查询
  30. *
  31. * @param title
  32. * @param content
  33. * @param min
  34. * @param max
  35. * @param page
  36. * @param rows
  37. * @return
  38. */
  39. Page<Item> findByTitleAndContentAndIdBetween(String title, String content, int min, int max, int page, int rows);
  40. }
  1. public class ItemServiceImpl implements ItemService {
  2. @Autowired
  3. private ItemRepository itemRepository;
  4. public Page<Item> findByPage(int page, int rows) {
  5. Page<Item> items = this.itemRepository.findAll(PageRequest.of(page, rows));
  6. return items;
  7. }
  8. public List<Item> findByTitleAndContent(String title, String content) {
  9. List<Item> list = this.itemRepository.findByTitleAndContent(title, content);
  10. return list;
  11. }
  12. public Page<Item> findByTitleOrContent(String title, String content, Integer page, Integer rows) {
  13. Page<Item> items = this.itemRepository.findByTitleOrContent(title, content, PageRequest.of(page - 1, rows));
  14. return items;
  15. }
  16. public Page<Item> findByTitleAndContentAndIdBetween(String title, String content, int min, int max, int page, int
  17. rows) {
  18. Page<Item> items = this.itemRepository.findByTitleAndContentAndIdBetween(title, content, min, max, PageRequest
  19. .of(page - 1, rows));
  20. return items;
  21. }
  22. }
    //分页查询数据
    @Test
    public void testFindByPage() {
        Page<Item> page = this.itemService.findByPage(1, 5);

        for (Item item : page.getContent()) {
            System.out.println(item);
        }
    }

    //复杂查询
    //根据title和Content进行查询,交集
    @Test
    public void testFindByTitleAndContent() {
        List<Item> list = this.itemService.findByTitleAndContent("SpringData ES 9", "今天我们使用SpringData ES完成job搜索功能。9");
        for (Item item : list) {
            System.out.println(item);
        }
    }


    //根据title或者Content进行分页查询,并集
    @Test
    public void testFindByTitleOrContent() {
        Page<Item> page = this.itemService.findByTitleOrContent("8", "9", 1, 5);

        for (Item item : page.getContent()) {
            System.out.println(item);
        }
    }


    //根据Title或者Content和Id的范围,进行分页查询
    @Test
    public void testFindByTitleAndContentAndIdBetween() {
        Page<Item> page = this.itemService.findByTitleAndContentAndIdBetween("ES", "job", 5, 9, 1, 10);

        for (Item item : page.getContent()) {
            System.out.println(item);
        }
    }

测试

10.1 测试分页查询

Spring Data ElasticSearch 常用API调用 - 图13

10.2 测试复杂查询,交集

Spring Data ElasticSearch 常用API调用 - 图14

10.3 测试分页查询,并集

Spring Data ElasticSearch 常用API调用 - 图15

10.4 测试分页查询和范围查询

Spring Data ElasticSearch 常用API调用 - 图16

11.单词条查询—自行编程

public interface ItemService {

    /**
     * 单词条查询
     * @param title
     * @param properties
     * @return
     */
    Iterable<Item> findBaseQuery(String title,String properties);
}
@Service
public class ItemServiceImpl implements ItemService {

    @Autowired
    private ItemRepository itemRepository;

        @Override
    public Iterable<Item> findBaseQuery(String title, String properties) {
        // 词条查询
        MatchQueryBuilder queryBuilder = QueryBuilders.matchQuery(title, properties);
        Iterable<Item> items = this.itemRepository.search(queryBuilder);
        return items;
    }
}
    // 根据title查询
    @Test
    public void testBaseQuery(){
        Iterable<Item> items = this.itemService.findBaseQuery("title", "ES");
        items.forEach(System.out::println);
    }

Spring Data ElasticSearch 常用API调用 - 图17

后续的各种自定义编程,可以参照elasticsearch-rest-high-level-client

基本上只需要NativeSearchQueryBuilder构建一下,其他代码完全按照实例抄一下就行。

https://blog.csdn.net/qq_41520636/article/details/116132943

结束!