es跨索引查询java代码
时间: 2023-09-25 07:06:20 浏览: 70
以下是使用 Elasticsearch Java API 进行跨索引查询的示例代码:
```java
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.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import java.io.IOException;
public class CrossIndexQueryExample {
public static void main(String[] args) throws IOException {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 9200, "http")));
SearchRequest searchRequest = new SearchRequest("index1", "index2");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchQuery("field1", "value1"));
searchSourceBuilder.size(10);
searchSourceBuilder.timeout(TimeValue.timeValueSeconds(10));
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
SearchHit[] searchHits = searchResponse.getHits().getHits();
for (SearchHit hit : searchHits) {
String sourceAsString = hit.getSourceAsString();
System.out.println(sourceAsString);
}
client.close();
}
}
```
这个示例查询了 `index1` 和 `index2` 两个索引中所有 `field1` 值为 `value1` 的文档,并输出它们的 JSON 字符串。可以根据实际需要修改查询条件和输出方式。
阅读全文