初始化
1.添加依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-elasticsearch</artifactId></dependency>
2.创建索引库
- 先创建好索引库以及映射信息
PUT /demo2{"mappings": {"properties":{"title":{"type":"text","analyzer":"ik_max_word"},"images":{"type":"keyword","index":"false"},"price":{"type":"float"},"type":{"type":"keyword"},"createDate":{"type":"date"}}}}
3.创建数据类
- 这里指定索引库为demo2
@Data@AllArgsConstructor@NoArgsConstructor@Document(indexName = "demo2")public class Goods implements Serializable {private static final long serialVersionUID = 1L;@Idprivate Integer id;private String title;private Double price;private String type;private String images;private Date createDate;}
4.创建配置
@Configurationpublic class RestClientConfig extends AbstractElasticsearchConfiguration {@Override@Beanpublic RestHighLevelClient elasticsearchClient() {final ClientConfiguration clientConfiguration = ClientConfiguration.builder().connectedTo("192.168.0.102:9200").build();return RestClients.create(clientConfiguration).rest();}}
Repository
1.创建接口
public interface GoodsRepository extends ElasticsearchRepository<Goods, Long> {}
2.保存数据
@AutowiredGoodsRepository goodsRepository;@Testpublic void addDocument(){Goods goods = new Goods(2,"华为手机",6999.0,"phone","huawei.jpg",new Date());goodsRepository.save(goods);}
3.高亮显示
- 接口添加方法
@Highlight(fields = {@HighlightField(name = "title")},parameters = @HighlightParameters(preTags = {"<font style='color:red'>"}, postTags = {"</font>"}))List<SearchHit<Goods>> findByTitle(String title);
- 调用方法
@Testpublic void findByTitle(){List<SearchHit<Goods>> phone = goodsRepository.findByTitle("手机");phone.forEach(s->{System.out.println(s.toString());});}
原生查询
1.新增数据
@Autowiredprivate ElasticsearchOperations elasticsearchOperations;@Testpublic void testCreateIndex() {Goods goods = new Goods(1,"小米手机",2999.0,"phone","mi.jpg",new Date());IndexCoordinates indexCoordinates =elasticsearchOperations.getIndexCoordinatesFor(goods.getClass());IndexQuery indexQuery = new IndexQueryBuilder().withId(goods.getId().toString()).withObject(goods).build();String documentId = elasticsearchOperations.index(indexQuery, indexCoordinates);System.out.println(documentId);}
官方文档 - https://docs.spring.io/spring-data/elasticsearch/docs/4.1.6/reference/html/#reference
更新时间:{docsify-updated}
