Elasticsearch 增删改查 Test01
package com.bw.test; import com.bw.bean.Book; import com.bw.esdao.BookRepository; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.common.text.Text; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHits; import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder; import org.elasticsearch.search.fetch.subphase.highlight.HighlightField; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.data.domain.Pageable; import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; import org.springframework.data.elasticsearch.core.SearchResultMapper; import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage; import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl; import org.springframework.data.elasticsearch.core.query.IndexQuery; import org.springframework.data.elasticsearch.core.query.NativeSearchQuery; import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; import org.springframework.data.elasticsearch.core.query.SearchQuery; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.annotation.Resource; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:spring.xml") public class Test01 { @Resource private ElasticsearchTemplate template; @Resource BookRepository repository; @Test public void creteIndex(){ boolean index = template.createIndex(Book.class); } @Test public void deleteIndex(){ boolean b = template.deleteIndex(Book.class); } @Test public void addDocument(){ Book book =new Book(1,"BCX3254154","《java进阶》","赵那个"); repository.save(book); } @Test public void addBulk(){ IndexQuery indexQuery = new IndexQuery(); List<IndexQuery> list=new ArrayList(); List<Book> list2=new ArrayList(); Book b1=new Book(10,"ERE6784644","《java基础1》","Jack1"); Book b2=new Book(2,"BCX3254184","《java基础2》","Jack2"); Book b3=new Book(3,"BCX3254185","《java基础3》","Jack3"); Book b4=new Book(4,"BCX3254186","《java基础4》","Jack4"); Book b5=new Book(5,"BCX3254187","《java基础5》","Jack5"); Book b6=new Book(6,"BCX3254188","《java基础6》","Jack6"); Book b7=new Book(7,"BCX3254189","《java基础7》","Jack7"); Book b8=new Book(8,"BCX3254196","《java基础8》","Jack8"); Book b9=new Book(9,"BCX3254199","《java基础9》","Jack9"); indexQuery.setObject(b1); indexQuery.setObject(b2); indexQuery.setObject(b3); indexQuery.setObject(b4); indexQuery.setObject(b5); indexQuery.setObject(b6); indexQuery.setObject(b7); indexQuery.setObject(b8); indexQuery.setObject(b9); list.add(indexQuery); list2.add(b1); list2.add(b2); list2.add(b3); list2.add(b4); list2.add(b5); list2.add(b6); list2.add(b7); list2.add(b8); list2.add(b9); //template.bulkIndex(list); repository.saveAll(list2); } @Test public void delById(){ repository.deleteById(5); } @Test public void queryById(){ Optional book = repository.findById(8); // Book book =(Book) optionalBook.get(); System.out.println(book); // NativeSearchQuery search = new NativeSearchQueryBuilder().withQuery(QueryBuilders.matchQuery("bid","8")).build(); // List<Book> list = template.queryForList(search, Book.class); // for (Book book : list) { // System.out.println(book); // QueryBuilder query = QueryBuilders.queryStringQuery("8"); // System.out.println(query); // // System.out.println("*********************"); // SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(query).build(); // System.out.println(searchQuery); //// // List<Book> list = template.queryForList(searchQuery, Book.class); // System.out.println(list); } //条件查询 根据名称 @Test public void list2(){ QueryBuilder query = QueryBuilders.queryStringQuery("进阶"); SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(query).build(); List<Book> list = template.queryForList(searchQuery, Book.class); System.out.println(list); } //高亮查询 @Test public void highlight(){ HighlightBuilder.Field field = new HighlightBuilder.Field("bname"); field.postTags("</span>"); field.preTags("<span style='color:red;'>"); field.fragmentSize(5); field.numOfFragments(1); NativeSearchQuery searchQuery=new NativeSearchQueryBuilder() .withQuery(QueryBuilders.matchQuery("bname","进阶")) .withHighlightFields(field) .build(); AggregatedPage<Book> page = template.queryForPage(searchQuery, Book.class, new SearchResultMapper() { @Override public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) { ArrayList<Book> bookList = new ArrayList<>(); SearchHits hits = response.getHits(); long totalHits = hits.totalHits; SearchHit[] hitsHits = hits.getHits(); for (SearchHit hitsHit : hitsHits) { Book book = new Book(); Map<String, Object> stringObjectMap = hitsHit.getSource(); String bid = stringObjectMap.get("bid") + ""; String number = stringObjectMap.get("number") + ""; String bname = stringObjectMap.get("bname") + ""; String author = stringObjectMap.get("author") + ""; Map<String, HighlightField> highlightFields = hitsHit.getHighlightFields(); if (highlightFields.containsKey("bname")){ HighlightField highlightField = highlightFields.get("bname"); Text[] fragments = highlightField.getFragments(); book.setBname(fragments[0].toString()); }else { book.setBname(bname); } book.setBid(Integer.parseInt(bid)); book.setNumber(number); book.setAuthor(author); bookList.add(book); } return new AggregatedPageImpl(bookList, pageable, totalHits); } }); List<Book> bookList = page.getContent(); for (Book book : bookList) { System.out.println(book); } } // @Test // public void testHiahLisht(){ // //配置一个高亮字段配置构建器 // HighlightBuilder.Field field = new HighlightBuilder.Field("bname"); // field.numOfFragments(1); //要几段 // field.fragmentSize(5); //每段多少字符 // field.preTags("<span style='color:red'>"); //前缀 // field.preTags("</span>"); //后缀 // // NativeSearchQuery query = new NativeSearchQueryBuilder().withHighlightFields(field) // .withQuery(QueryBuilders.matchQuery("bname", "骆驼祥子")) // .withPageable(PageRequest.of(0, 2)).build(); // // //做高亮查询一般用queryForList或者queryForPage // //用queryForList查出来结果没有高亮数据但是可以帮助我们自动封装对象 // //queryForPage搜索出来的结果它不能帮我们自动对象封装,但是包含高亮信息 // // //高亮查询 第一个参数条件 第二个参数类型,对应返回结果泛型 第三个参数 查询结果搜索结果的映射器,将搜索的结果转换成java对象 // // AggregatedPage<Book> page = elasticsearchTemplate.queryForPage(query, Book.class, new SearchResultMapper() { // // // // @Override // public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) { // // SearchHits searchHits = response.getHits(); // SearchHit[] hits = response.getHits().getHits(); // List<T> resultList = new ArrayList<>(); // // //每个SearchHit对应一个搜索结果对象 // for (SearchHit hit : hits) { // //source对应搜索结果中的_source数据。字段名是key,字段值是value // Map<String, Object> source= hit.getSourceAsMap(); // Book book = new Book(); // //处理source和对应的映射 // book.setBid(Integer.parseInt(source.get("bid").toString())); // book.setBname(source.get("bname").toString()); // book.setPrice(Double.parseDouble(source.get("price").toString())); // //book.setPic(source.get("pic").toString()); // // //处理高亮 // Map<String, HighlightField> highlightFieldMap = hit.getHighlightFields(); // if (highlightFieldMap.containsKey("bname")){ // //存在title对应的高亮数据 // HighlightField highlightField = highlightFieldMap.get("bname"); // Text[] texts = highlightField.getFragments(); // //一般只要数组的0下标位置 // String s = texts[0].toString(); // book.setBname(s); // }else{ // //没有高亮数据 // book.setBname(source.get("bname").toString()); // } // //加入到返回结果集合中 // resultList.add((T)book); // } // // return new AggregatedPageImpl<>(resultList,pageable,searchHits.getTotalHits()); // } // }); // // //总计数据行数 // long totalElements = page.getTotalElements(); // //总计页数 // int totalPages = page.getTotalPages(); // //当前页数数据集合 // List<Book> content = page.getContent(); // // System.out.println(totalElements); // System.out.println(totalPages); // System.out.println(content); // }
*************************************
package com.bw.bean; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.FieldType; @Data @NoArgsConstructor @AllArgsConstructor @Document(indexName="book_index",type="book_type",shards=5,replicas=0) public class Book { @Id private Integer bid; @Field(type = FieldType.text) private String number; @Field(type = FieldType.text,analyzer = "ik_max_word") private String bname; @Field(type = FieldType.keyword,index = false) private String author; @Override public String toString() { return "Book{" + "bid=" + bid + ", number='" + number + '\'' + ", bname='" + bname + '\'' + ", author='" + author + '\'' + '}'; } }
***********************************************
package com.bw.esdao; import com.bw.bean.Book; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; /** * ElasticsearchRepository: * 继承了JPA中原来的增删改查、分页 、排序等功能 * ElasticsearchRepository<Blog,Integer> * 第一个是要操作的类型 第二是主键类型 * 每声明一个接口只能操作对应的类型 如果有多个类型需要声明多个接口 * * springData Jpa自定义方法规则: * 方法名称必须是findBy readBy getBy 三者之一开头 * by后面可以拼接属性名称 属性名称首字母大写,后面再拼接关键字, * 如果有多个属性查询可以使用and或者or进行关联 * */ public interface BookRepository extends ElasticsearchRepository<Book,Integer> { } }