java实现es模糊查询
时间: 2023-09-20 09:14:42 浏览: 91
ElasticSearch整合JavaApi代码
以下是三种Java实现ES模糊查询的代码示例:
1. 使用match查询的代码实现方式:
```java
@Test
public void matchQuery() throws IOException {
//1. 创建Request对象
SearchRequest request = new SearchRequest(index);
request.types(type);
//2. 指定查询条件
SearchSourceBuilder builder = new SearchSourceBuilder();
builder.query(QueryBuilders.matchQuery("field", "keyword"));
request.source(builder);
//3. 执行查询
SearchResponse resp = client.search(request, RequestOptions.DEFAULT);
//4. 获取到_source中的数据,并展示
for (SearchHit hit : resp.getHits().getHits()) {
Map<String, Object> result = hit.getSourceAsMap();
System.out.println(result);
}
}
```
2. 使用term查询的代码实现方式:
```java
@Test
public void termQuery() throws IOException {
//1. 创建Request对象
SearchRequest request = new SearchRequest(index);
request.types(type);
//2. 指定查询条件
SearchSourceBuilder builder = new SearchSourceBuilder();
builder.query(QueryBuilders.termQuery("field", "value"));
request.source(builder);
//3. 执行查询
SearchResponse resp = client.search(request, RequestOptions.DEFAULT);
//4. 获取到_source中的数据,并展示
for (SearchHit hit : resp.getHits().getHits()) {
Map<String, Object> result = hit.getSourceAsMap();
System.out.println(result);
}
}
```
3. 使用wildcard查询的代码实现方式:
```java
@Test
public void wildcardQuery() throws IOException {
//1. 创建Request对象
SearchRequest request = new SearchRequest(index);
request.types(type);
//2. 指定查询条件
SearchSourceBuilder builder = new SearchSourceBuilder();
builder.query(QueryBuilders.wildcardQuery("field", "pattern"));
request.source(builder);
//3. 执行查询
SearchResponse resp = client.search(request, RequestOptions.DEFAULT);
//4. 获取到_source中的数据,并展示
for (SearchHit hit : resp.getHits().getHits()) {
Map<String, Object> result = hit.getSourceAsMap();
System.out.println(result);
}
}
```
以上是三种常见的Java实现ES模糊查询的方法,你可以根据具体的需求选择适合的方法来进行查询。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [Java操作ElasticSearch相关内容](https://blog.csdn.net/weixin_45892531/article/details/107946329)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]
阅读全文