如果你需要按照日期进行筛选,你可以使用 Elasticsearch 的范围查询来实现。以下是一个示例代码,演示如何在 Java 中进行日期范围查询:
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.SearchHit;import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;public class ElasticsearchQueryWithDateRange {public static void main(String[] args) {// Elasticsearch集群的主机和端口String hostname = "your_hostname";int port = 9200;// 认证信息String username = "your_username";String password = "your_password";// 构建认证final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();credentialsProvider.setCredentials(AuthScope.ANY,new UsernamePasswordCredentials(username, password));// 构建RestClientRestClientBuilder builder = RestClient.builder(new HttpHost(hostname, port)).setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));// 构建RestHighLevelClientRestHighLevelClient client = new RestHighLevelClient(builder);// 构建日期格式化对象SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");// 定义起始日期和结束日期Date startDate = ...; // 设置起始日期Date endDate = ...; // 设置结束日期// 构建搜索请求SearchRequest searchRequest = new SearchRequest("your_index_name");SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();// 添加日期范围查询条件searchSourceBuilder.query(QueryBuilders.rangeQuery("date_field_name").gte(dateFormat.format(startDate)).lt(dateFormat.format(endDate)));searchRequest.source(searchSourceBuilder);try {// 执行搜索请求SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);// 处理搜索结果for (SearchHit hit : searchResponse.getHits().getHits()) {// 读取每个搜索结果的数据String documentId = hit.getId();String documentSource = hit.getSourceAsString();System.out.println("Document ID: " + documentId);System.out.println("Document Source: " + documentSource);}} catch (IOException e) {e.printStackTrace();} finally {// 关闭客户端连接try {client.close();} catch (IOException e) {e.printStackTrace();}}}
}
在这个示例中,你需要将 date_field_name
替换为你的文档中实际存储日期的字段名称,同时设置合适的起始日期 startDate
和结束日期 endDate
。确保日期格式化对象的格式与你的日期字段格式匹配。
这个示例将执行一个范围查询,返回指定日期范围内的文档。