赞
踩
1. 创建springboot项目引入ES依赖
es与spring以及分词器要有严格的版本对应
2. 配置文件
spring:
elasticsearch:
rest:
uris: ip:9200
3. 配置客户端
@Configuration public class RestClientConfig extends AbstractElasticsearchConfiguration { @Value("${spring.elasticsearch.rest.uris}") private String uris; @Override public RestHighLevelClient elasticsearchClient() { final ClientConfiguration clientConfiguration = ClientConfiguration.builder() .connectedTo(uris) .withConnectTimeout(1000) .withSocketTimeout(30000) .build(); return RestClients.create(clientConfiguration).rest(); } }
4. 创建索引
定义常量字符串保存创建索引库
public class ShopConstants { public static final String MAPPING_TEMPLATE = "{\n" + "\"properties\":{\n" + "\"id\":{\n" + "\"type\":\"keyword\"\n" + "},\n" + "\"shopName\":{\n" + "\"type\":\"text\",\n" + "\"copy_to\":\"all\"\n" + "},\n" + "\"shopContent\":{\n" + "\"type\":\"text\",\n" + "\"index\":false\n" + "},\n" + "\"score\":{\n" + "\"type\":\"integer\"\n" + "},\n" + "\"userName\":{\n" + "\"type\":\"keyword\",\n" + "\"copy_to\":\"all\"\n" + "},\n" + "\"all\":{\n" + "\"type\":\"text\"\n" + "}\n" + "}\n" + "}"; }
restClient方式创建索引库
@Test
public void createIndex() {
try {
CreateIndexRequest createIndexRequest = new CreateIndexRequest("shop");
createIndexRequest.mapping(MAPPING_TEMPLATE, XContentType.JSON);
CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
log.info("创建索引状态:{}", createIndexResponse.isAcknowledged());
} catch (Exception e) {
log.info("创建失败:{}", e.getMessage());
}
}
这里需要注意的是,引入的CreateIndexRequest
是import org.elasticsearch.client.indices.CreateIndexRequest;
如果引入import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
d 的话需要这么写
createIndexRequest.mapping("_doc",MAPPING_TEMPLATE, XContentType.JSON);
5. 判断索引库是否存在
@Test
public void existsIndex() {
try {
GetIndexRequest indexRequest = new GetIndexRequest("shop");
boolean exists = restHighLevelClient.indices().exists(indexRequest, RequestOptions.DEFAULT);
log.info("索引是否存在:{}", exists);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
6. 删除索引库
@Test
public void delIndex() {
try {
AcknowledgedResponse shopIndex = restHighLevelClient.indices().delete(new DeleteIndexRequest("shop"), RequestOptions.DEFAULT);
log.info("删除索引:{}", shopIndex.isAcknowledged());
} catch (Exception e) {
log.info("删除失败:{}", e.getMessage());
}
}
7. 新增单条文档
@Test
public void createDoc() {
IndexRequest indexRequest = new IndexRequest("shop");
Shop shop = new Shop("1", "小米手机店铺", "小米手机买卖", 1, "张三");
indexRequest.id(shop.getId());
indexRequest.source(JSONUtil.toJsonStr(shop), XContentType.JSON);
try {
IndexResponse index = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
log.info("创建结果:{}", index.getResult());
} catch (Exception e) {
log.info("创建失败:{}", e.getMessage());
}
}
8. 单条查询文档
@Test
public void selectOneDoc() {
try {
GetRequest getRequest = new GetRequest("shop", "1");
GetResponse documentFields = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
log.info("查询结果:{}", documentFields.getSourceAsString());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
9. 修改文档
@Test
public void updateDoc() {
UpdateRequest updateRequest = new UpdateRequest("shop","1");
Shop shop = new Shop();
shop.setShopName("小米手机店铺123");
updateRequest.doc(JSONUtil.toJsonStr(shop), XContentType.JSON);
try {
UpdateResponse update = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
log.info("更新结果:{}", update.getResult());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
10. 删除文档
@Test
public void delDoc() {
DeleteRequest deleteRequest = new DeleteRequest("shop","1");
try {
DeleteResponse delete = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
log.info("删除结果:{}", delete.getResult());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
11. 批量导入文档
@Test public void batchCreateDoc() { try { Shop shop = new Shop("1", "小米手机店铺", "小米手机买卖", 1, "张三"); Shop shop2 = new Shop("2", "华为手机店铺", "华为手机买卖", 2, "李四"); Shop shop3 = new Shop("3", "苹果手机店铺", "苹果手机买卖", 3, "可子"); List<Shop> shopList = Arrays.asList(shop, shop2, shop3); BulkRequest bulkRequest = new BulkRequest(); for (Shop shop1 : shopList) { bulkRequest.add(new IndexRequest("shop") .id(shop1.getId()) .source(JSONUtil.toJsonStr(shop1), XContentType.JSON)); } BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT); //返回false表示没有失败的情况 log.info("批量创建结果:{}", bulk.hasFailures()); } catch (IOException e) { throw new RuntimeException(e); } }
12. 复杂查询
a 查询所有
@Test
public void selectDoc() {
SearchRequest searchRequest = new SearchRequest("shop");
searchRequest.source().query(QueryBuilders.matchAllQuery());
try {
SearchResponse documentFields = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHit[] hits = documentFields.getHits().getHits();
for (SearchHit hit : hits) {
log.info("查询结果:{}", hit.getSourceAsString());
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
b 多字段查询
@Test
public void selectDoc() {
SearchRequest searchRequest = new SearchRequest("shop");
searchRequest.source().query(QueryBuilders.multiMatchQuery("可子", "shopName", "userName"));
try {
SearchResponse documentFields = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHit[] hits = documentFields.getHits().getHits();
for (SearchHit hit : hits) {
log.info("查询结果:{}", hit.getSourceAsString());
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
c 精准查询
这里需要注意的是,设置为keyword
类型的字段才能使用精准查询
@Test
public void selectDoc() {
SearchRequest searchRequest = new SearchRequest("shop");
searchRequest.source().query(QueryBuilders.termQuery("userName", "可子"));
try {
SearchResponse documentFields = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHit[] hits = documentFields.getHits().getHits();
for (SearchHit hit : hits) {
log.info("查询结果:{}", hit.getSourceAsString());
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
d 范围查询
@Test
public void selectDoc() {
SearchRequest searchRequest = new SearchRequest("shop");
searchRequest.source().query(QueryBuilders.rangeQuery("score").gt(2));
try {
SearchResponse documentFields = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHit[] hits = documentFields.getHits().getHits();
for (SearchHit hit : hits) {
log.info("查询结果:{}", hit.getSourceAsString());
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。