第一步:引入依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-elasticsearch</artifactId><version>2.2.5.RELEASE</version></dependency>
第二步:配置yml文件,在spring下面加上这个
elasticsearch:rest:# ip是服务器ip地址uris: http://127.0.0.1:9200
然后启动项目,看到出现这个就是成功了
第三步: 创建一个常量类,用于存储我们一会儿要用到的名称
public class OrderEs {public static final String INDEX_NAME = "order_index";public static final String ID = "id";public static final String ORDER_NO = "order_no";public static final String ORDER_BUYER = "order_buyer";public static final String ORDER_PHONE = "order_phone";public static final String REAL_PAY = "real_pay";public static final String ACCOUNT = "account";
}
第四步:创建Es实体类,注意要加上@Document注解
@Document(indexName = OrderEs.INDEX_NAME)
@Data
public class OrderEsPO {@Id@Field(type = FieldType.Keyword,name = OrderEs.ID)private String id;@Field(type = FieldType.Keyword,name = OrderEs.ORDER_NO)private String orderNo;@Field(type = FieldType.Keyword,name = OrderEs.ORDER_BUYER)private String orderBuyer;@Field(type = FieldType.Keyword,name = OrderEs.ORDER_PHONE)private String orderPhone;@Field(type = FieldType.Keyword,name = OrderEs.REAL_PAY)private String realPay;@Field(type = FieldType.Keyword,name = OrderEs.ACCOUNT)private String account;}
第五步:写测试接口,这里展示了插入和查询两个方法
@RestController
@RequestMapping("/order")
@CrossOrigin
public class OrderController @Resourceprivate ElasticsearchRestTemplate elasticsearchRestTemplate;/*** es插入** @return {@link String}*/@GetMapping("/esinsert")@Transactionalpublic String esInsert(){OrderEsPO orderEsPO = new OrderEsPO();orderEsPO.setOrderNo("1234455");orderEsPO.setOrderBuyer("张三");orderEsPO.setOrderPhone("13191892075");orderEsPO.setRealPay("100000");orderEsPO.setAccount("1008611");elasticsearchRestTemplate.save(orderEsPO);return "success";}/*** es搜索** @param orderEsPO 订单es参数* @return {@link String}*/@GetMapping("/essearch")@Transactionalpublic String esSearch(OrderEsPO orderEsPO){/**构造查询对象**/BoolQueryBuilder booleanQueryBuilder = QueryBuilders.boolQuery();/**编写查询条件**/booleanQueryBuilder.should(QueryBuilders.termQuery(OrderEs.ORDER_NO,orderEsPO.getOrderNo()));/**构造query对象**/NativeSearchQuery nativeSearchQuery = new NativeSearchQuery(booleanQueryBuilder);/**搜索**/SearchHits<OrderEsPO> search = elasticsearchRestTemplate.search(nativeSearchQuery, OrderEsPO.class, IndexCoordinates.of(OrderEs.INDEX_NAME));List<OrderEsPO> collect = search.getSearchHits().stream().map(SearchHit::getContent).collect(Collectors.toList());return collect.toString();}
}
然后我们启动项目,先调用插入接口,由于这个索引一开始是不存在的,第一次调用后会默认创建索引,然后打开我们的可视化界面,就能看到这里的索引
再调用查询,就能看到如下信息了
说明两个接口都能被调用成功,es的简单使用就完成了