es模糊查询用java实现
时间: 2023-09-20 21:12:30 浏览: 96
可以使用Java中的Elasticsearch Java API来实现ES模糊查询。下面是一个简单的示例代码:
```java
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import java.io.IOException;
public class ESQueryExample {
public static void main(String[] args) throws IOException {
RestHighLevelClient client = new RestHighLevelClient();
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
QueryBuilder queryBuilder = QueryBuilders.fuzzyQuery("field_name", "search_term");
sourceBuilder.query(queryBuilder);
SearchRequest searchRequest = new SearchRequest("index_name");
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = client.search(searchRequest);
SearchHits hits = searchResponse.getHits();
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
client.close();
}
}
```
在上面的代码中,我们使用了ES的Fuzzy Query来实现模糊查询。其中,"field_name"是要查询的字段名,"search_term"是要查询的关键词。你需要将"index_name"替换成你要查询的索引名称,然后就可以运行代码来进行查询了。
阅读全文