Tests using advanced query index database crud and pagination

Setting up an ES service
  • Import dependence

     <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
    </dependency>
  • ES configuration

    ... 
    Spring: 
      file application: 
        name: ES-HRM-Service- 
      Data: 
        elasticsearch: 
          Cluster-name: elasticsearch 
          Cluster Nodes-: 127.0.0.1:9300 # 9200 is a graphical interface terminal end codes 9300 
          ... 
2. Create EmployeeDoc
/ ** 
 * Documentation for mapping to the Employee table 
 * indexName: index Library 
 * type: type (table type) 
 * / 
@Document (indexName = "HRM", of the type = "the Employee" )
 public  class EmployeeDoc { 
    // corresponding document of the above mentioned id 
    the @Id
     Private Long the above mentioned id; 
    @Field (of the type = FieldType.Keyword)     // designated as a word regardless of 
    Private String userName; 
    Private  int Age; 
    @Field (of the type = FieldType.Text, Analyzer = "ik_max_word", searchAnalyzer = "ik_max_word" )
     Private String INTR; 
    ...
3. Create an index Library
@RunWith(SpringRunner.class)
@SpringBootTest(classes = EsServiceApplication2050.class)
public class ESTest {
​
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;
​
    @Test
    public void testCreateIndex() {
        //创建索引
        elasticsearchTemplate.createIndex(EmployeeDoc.class);
        //做文档映射
        elasticsearchTemplate.putMapping(EmployeeDoc.class);
    }
}
4. Define ElasticsearchRepository
@Repository
public interface EmployeeElasticsearchRepository  extends ElasticsearchRepository<EmployeeDoc,Long> {}
5. The basic CRUD
@Autowired
     Private EmployeeElasticsearchRepository employeeElasticsearchRepository; 
    // initialize 
    @Test
     public  void testCreateIndex () {
         // create an index 
        elasticsearchTemplate.createIndex (EmployeeDoc. Class );
         // do document mapping 
        elasticsearchTemplate.putMapping (EmployeeDoc. Class ); 
    } 
    // add data 
    @Test
     public  void testAdd () { 
        // prepare data 
        employeeDoc employeeDoc = new new  EmployeeDoc ();
        employeeDoc.setAge ( 18 is ); 
        employeeDoc.setUserName ( "King sledgehammer" ); 
        employeeDoc.setIntr ( "I love China" ); 
        // add data to es 
        employeeElasticsearchRepository.save (employeeDoc); 
    } 
    // add data 
    @Test
     public  void testUpdate () { 
        // prepare data 
        EmployeeDoc employeeDoc = new new EmployeeDoc (); 
        employeeDoc.setId ( 5L);   // there is a change id 
        employeeDoc.setAge (18 is ); 
        employeeDoc.setUserName ( "Botong" );
        employeeDoc.setIntr ( "boy won on the true mass" ); 
        // add data to ES 
        employeeElasticsearchRepository.save (employeeDoc); 
    } 
    // delete the data 
    @Test
     public  void TestDelete () { 
        employeeElasticsearchRepository.deleteById ( 5L ); 
    } 
    // acquiring data 
    @Test
     public  void testGet () { 
        optional The <EmployeeDoc> = optional employeeElasticsearchRepository.findById (5L ); 
        System.out.println (optional.get ()); 
    }
6. Advanced Search page
    
// By indexing the library, paging and advanced query 
    / ** 
     * user name is next door Pharaoh 
     * age at 10--20 
     * sorted in descending order according to id 
     * page per page 2 take the first page 
     * / 
    @Test 
    public  void testSearchAndPage () throws Exception {
         // 1. Create a query builder objects 
        NativeSearchQueryBuilder QueryBuilder = new new NativeSearchQueryBuilder (); 
        // 2. Add the query object to the query builder
             // 1. create a combined query objects 
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery () ;
             // 2. Add search criteria: word query: username 
        List <QueryBuilder> = the MUST boolQuery.must ();
        must.add (QueryBuilders.matchQuery ( "username", "Botong" ));
             // 2. Add Query: range query: age: 10 to 30 
        List <the QueryBuilder> filter = boolQuery.filter (); 
        filter.add ( QueryBuilders.rangeQuery ( . "Age") lte (30) .gte (10 ));
             // 3. Add query object to the query builder 
        queryBuilder.withQuery (boolQuery); 
        // 3. Add a page to the query builder Object: from 0 start, page 2 
        queryBuilder.withPageable (PageRequest.of (0,2 )); 
        // 4. query Builder to add sorting
             // 1. create a sort object: id, descending 
        FieldSortBuilder sortBuilder = new new FieldSortBuilder ( "the above mentioned id") .order (SortOrder.DESC);
             // 2. Query Builder to add sorting 
        queryBuilder.withSort (sortBuilder); 
        // 5. The object is to create a query 
        NativeSearchQuery searchQuery = queryBuilder.build (); 
        // 6. The pass search method, performing advanced queries paging sort function, to give the object tab 
        Page <EmployeeDoc> = Page employeeElasticsearchRepository.search (searchQuery); 
        // 7. The acquisition result
             // get the total number of 
        int totalpages = page.getTotalPages (); 
        the System. Out.println (totalpages); 
            // get this page data 
        the Iterator <EmployeeDoc> Iterator = page.getContent () Iterator ();.
         the while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }

 

 

Guess you like

Origin www.cnblogs.com/htq29study/p/11617266.html