在Java中使用Elasticsearch直接使用JSON查詢非常方便。通過使用Java中的Elasticsearch API,我們可以輕松地編寫JSON查詢。以下是一些使用JSON查詢的示例。
import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.builder.SearchSourceBuilder; import java.io.IOException; public class JSONQueryExample { private RestHighLevelClient client; public void someMethod() throws IOException { SearchRequest searchRequest = new SearchRequest("index-name"); BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery(); queryBuilder.must(QueryBuilders.matchQuery("field1", "value1")); queryBuilder.must(QueryBuilders.termQuery("field2", "value2")); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); sourceBuilder.query(queryBuilder); searchRequest.source(sourceBuilder); SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT); SearchHit[] hits = searchResponse.getHits().getHits(); for (SearchHit hit : hits) { System.out.println(hit.getSourceAsString()); } } }
以上代碼使用JSON查詢來搜索Elasticsearch中的文檔。代碼首先創建一個搜索請求,指定要搜索的索引名稱。然后,它創建一個布爾查詢構建器,并添加兩個查詢條件。最后,它創建一個搜索源構建器,并設置查詢條件,然后將其分配給搜索請求。搜索響應包含與查詢匹配的文檔,我們可以使用SearchHit對象來訪問這些文檔。在這里,我們只是將文檔打印到控制臺上。