1. Springboot integrates ES

Create springboot project my-springboot-es, add Lombok and spring-boot-starter-data-elasticSearch dependencies.

  • Springboot uses 2.3.1.release.
  • Elasticsearch uses version 7.6.0.

Configuration: added in pom.xml

<! --spring-boot-starter-data-elasticsearch-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
Copy the code

2. The configuration

Concept: Specify ES server location or, if cluster, separate addresses with commas.

Configuration: added in application.properties

spring.elasticsearch.rest.uris: http://localhost:9200
Copy the code

3. The entity class

Concept:

  • @Document: An entity class is a document, usedindexNameProperty to specify the index name, which is automatically created if ES does not have it.
  • @Id: Identifies a primary key field. Optional.
  • @Field: Identifies a common field. This field is optional.
/ * * *@author yap
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Document(indexName = "test-index")
public class User implements Serializable {

    @Id
    private Integer id;

    @Field(type = FieldType.Text)
    private String name;

    @Field(type = FieldType.Text)
    private String about;
}
Copy the code

4. Data layer development

Concept: Create an empty interface that inherits ElasticsearchRepository to use the ES API.

  • @RepositoryMake it managed by the Spring container.
  • ElasticsearchRepositoryThe two generics are document type and primary key type.

Source: UserRepository. Java

/ * * *@author yap
 */
@Repository
public interface UserRepository extends ElasticsearchRepository<User.Integer> {}Copy the code

5. Test

Source: ElastciSearchTest. Java

/ * * *@author yap
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MySpringdataEsApplication.class)
class ElastciSearchTest {

    @Autowired
    private UserRepository userRepository;

    @Test
    void save(a) {
        User user = new User(1."Test Name"."Description"); userRepository.save(user); }}Copy the code

Test interface: GET localhost:9200/test-index/_doc/1

First complete springDatA2 (5) ES basic introduction.

crud

1. Repository

Concept: Repository is the central Repository markup interface and the topmost interface of the ES operation interface.

Inheritance relationship:

| _ Repository: central Repository marker interface | _ CrudRepository: | _ PagingAndSortingRepository CRUD interface: paging and sorting operation interface | _ ElasticsearchRepository: ES warehouse interface | _ UserRepository: custom user interfaceCopy the code

2. CrudRepository

Concept: CrudRepository provides some common add, delete, change apis:

  • <S extends T> S save(S entity);: Indexes a single document
  • <S extends T> Iterable<S> saveAll(Iterable<S> entities);: Indexes multiple documents
  • Optional<T> findById(ID id);: Retrieves the specified document by ID
  • boolean existsById(ID id);: Verifies the existence of the specified document by ID
  • Iterable<T> findAll();: Retrieves all documents
  • Iterable<T> findAllById(Iterable<ID> ids);: Retrieves multiple specified documents from the ID list
  • long count();: Retrieves the number of documents
  • void deleteById(ID id);: Deletes the specified document by ID
  • void delete(T entity);: Deletes the specified document through the document object
  • void deleteAll(Iterable<? extends T> entities);: Deletes the specified document from the document object list
  • void deleteAll();: Deletes all documents

2.1 the save/saveAll

Source code: Elastcisearchtest.java added

@Test
void save(a) {
    User user = new User(1."Test Name"."Description");
    userRepository.save(user);
}
    
@Test
void saveAll(a) {
    List<User> users = new ArrayList<>();
    User user01 = new User(2."Grant of Additional Name 02"."Batch Increment Information 02");
    User user02 = new User(3."Grant of Additional Name 03"."Batch Add Information 03");
    User user03 = new User(4."Grant of Additional Name 04"."Batch Increment Message 04");
    User user04 = new User(5."Additional Name 05"."Batch Add Information 05");
    users.add(user01);
    users.add(user02);
    users.add(user03);
    users.add(user04);
    userRepository.saveAll(users);
}
Copy the code

Adding the same ID document multiple times is considered a modification operation.

2.2 findById/existsById

Source code: Elastcisearchtest.java added

@Test
void findById(a){
    User user = null;
    Optional<User> userOp = userRepository.findById(1);
    if(userOp.isPresent()){
        user = userOp.get();
    }
    System.out.println(user);
}

@Test
void existsById(a){
    System.out.println(userRepository.existsById(1));
}
Copy the code

Optional is a new class in JDK1.8 that allows the inclusion of null values. It contains a number of methods for handling null values. IsPresent () is used to gracefully determine whether a variable is null.

2.3 findAll/findAllById/count

Source code: Elastcisearchtest.java added

@Test
public void findAll(a) {
    Iterable<User> usersIterable = userRepository.findAll();
    usersIterable.forEach(System.out::println);
}

@Test
public void findAllById(a) {
    List<Integer> ids = new ArrayList<>();
    ids.add(1);
    ids.add(2);
    Iterable<User> usersIterable = userRepository.findAllById(ids);
    usersIterable.forEach(System.out::println);
}

@Test
public void count(a) {
    System.out.println(userRepository.count());
}
Copy the code

2.4 deleteById/delete/deleteAll

Source code: Elastcisearchtest.java added

@Test
public void deleteById(a) {
    userRepository.deleteById(1);
}

@Test
public void delete(a) {
    User user = new User();
    // You must fill in the ID
    user.setId(3);
    userRepository.delete(user);
}

@Test
public void deleteAll(a) {
    List<User> users = new ArrayList<>();
    User user11 = new User(11.""."");
    User user12 = new User(12.""."");
    users.add(user11);
    users.add(user12);

    // Enter a list of entities whose ids are not empty. If this parameter is not specified, all the entities are deleted
    userRepository.deleteAll(users);
}
Copy the code

3. PagingAndSortingRepository

Concept: Provides two interface methods for sorting and paging queries:

  • Iterable<T> findAll(Sort sort);: Injects Sort objects to Sort the query results.
  • Page<T> findAll(Pageable pageable);: Injects Pageable objects to Pageable query results.

3.1 Query Sorting

Source code: Elastcisearchtest.java added

@Test
public void findSortedAll(a) {
    Sort descSortById = Sort.by("id").descending();
    Iterable<User> usersIterable = userRepository.findAll(descSortById);
    // Quick forEach traversal
    usersIterable.forEach(System.out::println);
}
Copy the code

3.2 Query Paging

Source code: Elastcisearchtest.java added

@Test
public void findBySort(a) {
    Sort sort = Sort.by("id").descending();
    Iterable<User> usersIterable = userRepository.findAll(sort);
    usersIterable.forEach(System.out::println);
}

@Test
void findByPage(a) {
    // p3 can be omitted
    Pageable page = PageRequest.of(0.3, Sort.by("id"));
    if (page.isPaged()) {
        Page<User> users = userRepository.findAll(page);
        System.out.println("Current page:" + page.getPageNumber());
        System.out.println("Page size:" + page.getPageSize());
        System.out.println("Total entries:" + users.getTotalElements());
        System.out.println("Total pages:"+ users.getTotalPages()); users.forEach(System.out::println); }}Copy the code

4. ElasticsearchRepository

Concept:

  • ElasticsearchRepositorySome apis are provided, but most are outdated.
  • UserRepositoryinheritedElasticsearchRepositoryIs our custom ES search API library.
  • We can do it atUserRepositoryCustomize API methods using certain keywords in:
    • Supported keywords are as follows:Like / Not / And / Or / Between / OrderByEtc., can be used in combination.
    • Method format Example: Return values areList<User>
    • findByName(String name): Retrieves all documents named XXX.
    • findOrderByName(String name)Sort all documents in reverse order by name.
    • findByNameLike(String name): Fuzzy retrieves all documents with the name XXX.
    • findByNameNot(String name): Retrieves all documents whose name is not XXX.
    • findByNameStartingWith(String prefix): Retrieves all documents whose names start with XXX.
    • findByNameEndingWith(String suffix): Retrieves all documents whose names end in XXX.
    • findByNameContaining(String content): Retrieves all documents whose total name contains XXX.
    • findByNameIn(List names): Retrieves all documents whose names are in the list XXX.
    • findByNameNotIn(List names): Retrieves all documents whose names are not in the list XXX.
    • findByGenderTrue(boolean gender): Retrieves all documents with gender true.
    • findByGenderFalse(boolean false): Retrieves all documents with gender false.
    • findByNameAndAbout(String name, String about): according to thenameaboutQuery documents that meet both criteria.
    • findByNameOrAbout(String name, String about): according to thenameaboutQuery any document that meets the criteria.
    • findByIdBetween(Integer min, Integer max): Retrieves all documents with ids between XXX and XXX.
    • findByIdLessThan(Integer num): Retrieves all documents with ids less than XXX.
    • findByIdGreaterThan(Integer num): Retrieves all documents whose ID is greater than XXX.
    • And so on.

Interface methods in Idea will be prompted.

Source code: userRepository.java added

/** * find all documents by name *@paramThe name name *@returnList of documents that meet the criteria */
List<User> findByName(String name);
Copy the code

Source code: Elastcisearchtest.java added

@Test
public void findByName(a) {
    List<User> users = userRepository.findByName("Grant of Additional Name 01");
    users.forEach(System.out::println);
}
Copy the code