SpringDataElasticSearch framework

dependencies
<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>2.3.2. RELEASE</version>
	<relativePath/> 
</parent>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<properties>
	<java.version>1.8</java.version>
	<elasticsearch.version>7.10.2</elasticsearch.version>
</properties>
Copy the code
Configuration yml
spring:
  elasticsearch:
    rest:
      uris:
        - xxx.xxx.xxx.xxx:9200
Copy the code
Configure the mapping between the entity class and Document
  1. @Document(indexName = “cube_goods”, shards = 5, replicas = 1)// Configure the corresponding index library, fragment number, and duplicate number
  2. @id // Specify an Id
  3. @Field(index = true, store = true, type = FieldType.Text, analyzer = “ik_smart”)

@Data
@Document(indexName = "blog_1", shards = 5, replicas = 1)
public class Blog {
    @Id
    @Field(type = FieldType.Long)
    private long id;
    @Field(type = FieldType.Text, analyzer = "ik_max_word", store = true)
    private String title;
    @Field(type = FieldType.Text, analyzer = "ik_max_word")
    private String content;
    @Field(type = FieldType.Text, analyzer = "ik_max_word", store = true)
    private String comment;
    @Field(type = FieldType.Keyword, store = true)
    private String mobile;
}
Copy the code
ElasticSearchRepository interface for managing documents
Method of use

Create an interface that inherits ElasticSearchRepository and specifies the Entity class to use and the corresponding primary key data type. Springboot automatically scans the interface and creates proxy objects

  1. Add or update data
    • Use the repository save method
  2. Delete the data
    • deleteById
    • deleteAll
  3. Query data
    • You can use the query methods that come with Repository
      • findById
      • findAll
    • You can customize the query method
      • findBy{Titlte}And{contnet}(String title, String content); By defining the method according to the naming convention, the corresponding query can be implemented
public interface BlogRepostory extends ElasticsearchRepository<Blog.Long> {
    // Define the method according to the naming convention
    List<Blog> findByTitle(String title);
    List<Blog> findByContent(String content, Pageable page);
}

@RunWith(SpringRunner.class)
@SpringBootTest
public class BlogRepostoryTest {
    @Autowired
    private BlogRepostory repostory;

    @Test
    public void testFindByTitle(a) {
        List<Blog> blogs = repostory.findByTitle("Film");
        blogs.forEach(System.out::println);
    }

    @Test
    public void testFindByPage(a) {
        List<Blog> list = repostory.findByContent("Film", PageRequest.of(0.5)); list.forEach(e-> System.out.println(e)); }}Copy the code
useElasticSearchRestTemplateObject (used for complex queries)
1) Create index libraries

​ template.indexOps(IndexCoordinates.of(“mytest”)).create();

2) Set the Mapping information

You need to create an entity class that configures the mapping between the entity class and the document, using annotations

You can generate mapping information from an Entity

@RunWith(SpringRunner.class)
@SpringBootTest
public class ElasticSearchTemplateTest {
    @Autowired
    private ElasticsearchRestTemplate template;

    @Test
    public void createIndex(a) {
        //template.indexOps(Blog.class).create(); // Created from the entity class
        template.indexOps(IndexCoordinates.of("hello_1")).create();// Create by name
    }

    @Test
    public void putMappiing(a) {
        Document mapping = template.indexOps(Blog.class).createMapping();// Created from the entity classtemplate.indexOps(Blog.class).putMapping(mapping); }}Copy the code
3) the query
  1. Encapsulate the query condition NativeSearchQuery

  2. SearchHits SearchHits = template.search(query, blog.class);

  3. The result processing

    • Searchhits.gettotalhits (); searchhits.getTotalhits ();

    • List

      searchHits1 = searchhits.getsearchhits (); List

      searchHits1 = searchhits.getsearchhits (); Then traverse

      • LLDB etContent()

      • HighlightFields = LLDB Map

        highlightFields = LLDB etHighlightFields();
        ,>

        List title = highlightFields.get(“title”);

      • Aggregate the results Map < String, Aggregation > stringAggregationMap = searchHits. The getAggregations () asMap ();

        Aggregation aggregation = stringAggregationMap.get(“mobile_count”);

        ParsedValueCount valueCount = searchHits.getAggregations().get(“mobile_count”);

        System.out.println(aggregation.getName());System.out.println(valueCount.getValue());


    @Test
    public void testQuery(a) {
        NativeSearchQuery query = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.termQuery("title"."Film"))
                .withHighlightBuilder(new HighlightBuilder().field("title").preTags("<em>").postTags("</em>"))
                .withFilter(QueryBuilders.termQuery("title"."Hunan"))
                .addAggregation(AggregationBuilders.count("mobile_count").field("mobile"))
                .build();
        SearchHits<Blog> searchHits = template.search(query, Blog.class);
        long totalHits = searchHits.getTotalHits();
        System.out.println(totalHits);
        List<SearchHit<Blog>> searchHits1 = searchHits.getSearchHits();
        searchHits1.forEach(e->{
            Blog content = e.getContent();
            System.out.println(content);
            Map<String, List<String>> highlightFields = e.getHighlightFields();
            List<String> title = highlightFields.get("title");
            System.out.println(title);
        });
        Map<String, Aggregation> stringAggregationMap = searchHits.getAggregations().asMap();
        System.out.println(stringAggregationMap);
        Aggregation aggregation = stringAggregationMap.get("mobile_count");
        ParsedValueCount valueCount = searchHits.getAggregations().get("mobile_count");
        System.out.println(aggregation == valueCount);
        System.out.println(aggregation.getName());
        System.out.println(valueCount.getValue());
    }
Copy the code