“This is the third day of my participation in the November Gwen Challenge. See details of the event: The last Gwen Challenge 2021”.

1. Add maven dependencies

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.6. RELEASE</version>
		<relativePath /> 
	</parent>
	
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
		</dependency>
	</dependencies>
Copy the code

2.application.yml

spring:
  application:
    name: senta-es
  data:
    elasticsearch:
      cluster-name: elasticsearch  #es Default cluster name
      cluster-nodes: 122.51226.121.: 9300  #9200 is the graphical interface side,9300 code side
      repositories:
        enabled: true   # Open Elasticsearch repository (default :true)
      properties:
        transport:
          tcp:
            connect_timeout: 120s  # ES Set connection timeout
Copy the code

3. Entity class layer


import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;

/** * The corresponding entity class *@authorDocument corresponds to a Document data indexName indexName type type */
@Document(indexName = "myIndexName", type = "user")
@Data
public class UserEntity {
    @Id
    private String id;
    private String name;
    private int sex;
    private int age;
}

Copy the code

4. The Dao class layer

import com.senta.elasticsearch.entity.UserEntity;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

/ * * *@authorFukobayashi * operates on the data layer */ corresponding to ES
@Repository
public interface UserRepository  extends CrudRepository<UserEntity.String> {}Copy the code

5. The Controller layer


import com.senta.elasticsearch.entity.UserEntity;
import com.senta.elasticsearch.mapper.xml.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

/ * * *@authorFukuobayashi * operates the controller of ES */
@RestController
public class EsController {

    @Autowired
    private UserRepository userRepository;

    @RequestMapping("/addUser")
    public UserEntity addUser(@RequestBody UserEntity user) {
        return userRepository.save(user);
    }

    @RequestMapping("/findUser")
    public Optional<UserEntity> findUser(String id) {
        returnuserRepository.findById(id); }}Copy the code

6. Start the project

@SpringBootApplication
public class ESApplication {

	public static void main(String[] args) { SpringApplication.run(ESApplication.class, args); }}Copy the code

7. If the Repostitory scan fails

/ * * *@authorFu xiao Lin * if scanning UserRepository failure, then you need to add E @ nableElasticsearchRepositories * /
@SpringBootApplication
@EnableElasticsearchRepositories(basePackages = "com.senta.repository")
public class ESApplication {

	public static void main(String[] args) { SpringApplication.run(ESApplication.class, args); }}Copy the code

8. Integrate with DSL statements

8.1 Summary of Common DSL Statements

SELECT * FROM billingitemdis WHERE orderDoctor=' orderDoctor 'AND patientName=' orderDoctor' AND itemClass1! ='E' AND orderDoctorId='12884' limit 0,308 ORDEY BY pk ASC
GET billing/billingitemdis/_search
{
    "query": {"bool": {"must":[
                {
                    "match": {"orderDoctor":"Wang Lin Sue"}}, {"match": {"patientName":"NieYan"}}]."must_not":[
                {
                    "match": {"itemClass1":"E"}}]."should":[
                {
                    "match": {"hosOutp":"Hospital"}}, {"match": {"itemClass2":"Treatment"}}]."filter": {"term": {"orderDoctorId":"12884"}}}},"sort":[
        {
            "pk": {"order":"asc"}}]."size": 308,"from":0
}
Copy the code

The order in which a query needs to be executed overwrites most of the commonly used orders. When creating a query in Java code, you should follow the order and hierarchy above, otherwise there is the possibility of error

8.2 Parameter Description

# queryOutermost query structure# boolYou can add: must, must_not, should, filter# mustYou can use match to match multiple conditions. Each condition must exist## must_notMatches can be made by match, and those that meet the criteria will be filtered out#shouldMultiple conditions can be matched through match, and correlation calculation of each match is consistent. If correlation needs to be adjusted, bool can be added to SHOULD for stimulus matching, and data of item matching is sorted according to correlation _score# filterFilter, through the term to accurately filter conditions, only the successful matching of the full word through# sort descSorting, I can save writing"sort": "pk" 

# sizeES has a default size that can be set using _settings, and may be page limit if not all data is displayed# fromThe current page, starting from 0, returns the fastest on the first page due to the ES feature. The time to access data increases as the page depth increases. Deep paging is not recommendedCopy the code

8.3 Corresponds to the Java code for DSL above

@GetMapping("/query")
public Page<BillingItemDis> queryFromEs(a){

    NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
    BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
    MatchQueryBuilder matchOderDoctor = QueryBuilders.matchQuery("orderDoctor"."Wang Lin Sue");
    MatchQueryBuilder matchPatientName = QueryBuilders.matchQuery("patientName"."NieYan");

    boolQuery.must(matchOderDoctor);
    boolQuery.must(matchPatientName);

    MatchQueryBuilder matchItemClass1 = QueryBuilders.matchQuery("itemClass1"."E");
    boolQuery.mustNot(matchItemClass1);

    MatchQueryBuilder matchHosOutp = QueryBuilders.matchQuery("hosOutp"."Hospital");
    MatchQueryBuilder matchItemClass2 = QueryBuilders.matchQuery("itemClass2"."Treatment");
    boolQuery.should(matchHosOutp);
    boolQuery.should(matchItemClass2);


    TermQueryBuilder termOrderDoctorId = QueryBuilders.termQuery("orderDoctorId"."12884");
    boolQuery.filter(termOrderDoctorId);

    builder.withQuery(boolQuery);

    builder.withSort(SortBuilders.fieldSort("pk").order(SortOrder.DESC));

    builder.withPageable(PageRequest.of(0.308));

    NativeSearchQuery searchQuery = builder.build();
    
    Page<BillingItemDis> search = billingItemDisRepository.search(searchQuery);

    return search;
}
Copy the code

8.4 Field Definition Specifications

Term cannot be matched and is saved as string. Range and Integer are not supported. Long: indicates the basic data type. The format can be used to define a side value. You are advised to use Float when filtering dates. Double: indicates a Double precision. Nested object data type, will form a specific association relationship, update associated parent-child object will update the entire database parent-child, use and query, occasionally update scenarios Ip: save Ip address with Attachment: Attachment type, doc, XML Keyword: Keywords, the default word, can match exactly, requirements name must be the DateFormat keyword fields: date type corresponding to the other format, please refer to http://www.kyjszj.com/htzq/109.htmlCopy the code