Remove more explicit SearchResponse references from test code (#100985)

Follow-up to #100966 adding more overrides to assertions that
consume a request builder.
This commit is contained in:
Armin Braun 2023-10-18 07:20:01 +02:00 committed by GitHub
parent 96184ddb13
commit dcaba064dd
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
30 changed files with 348 additions and 340 deletions

View file

@ -57,6 +57,7 @@ import static org.elasticsearch.search.aggregations.AggregationBuilders.sum;
import static org.elasticsearch.search.aggregations.AggregationBuilders.terms; import static org.elasticsearch.search.aggregations.AggregationBuilders.terms;
import static org.elasticsearch.search.aggregations.AggregationBuilders.topHits; import static org.elasticsearch.search.aggregations.AggregationBuilders.topHits;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse;
import static org.hamcrest.Matchers.closeTo; import static org.hamcrest.Matchers.closeTo;
import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.containsString;
@ -513,16 +514,15 @@ public class TimeSeriesAggregationsIT extends AggregationIntegTestCase {
.get(); .get();
QueryBuilder queryBuilder = QueryBuilders.rangeQuery("@timestamp").lte("2021-01-01T00:10:00Z"); QueryBuilder queryBuilder = QueryBuilders.rangeQuery("@timestamp").lte("2021-01-01T00:10:00Z");
SearchResponse response = client().prepareSearch("test")
.setQuery(queryBuilder)
.setSize(10)
.addSort("key", SortOrder.ASC)
.addSort("@timestamp", SortOrder.ASC)
.get();
assertSearchResponse(response);
response = client().prepareSearch("test").setQuery(queryBuilder).setSize(10).addAggregation(timeSeries("by_ts")).get(); assertNoFailures(
assertSearchResponse(response); client().prepareSearch("test")
.setQuery(queryBuilder)
.setSize(10)
.addSort("key", SortOrder.ASC)
.addSort("@timestamp", SortOrder.ASC)
);
assertNoFailures(client().prepareSearch("test").setQuery(queryBuilder).setSize(10).addAggregation(timeSeries("by_ts")));
assertAcked(indicesAdmin().delete(new DeleteIndexRequest("test")).actionGet()); assertAcked(indicesAdmin().delete(new DeleteIndexRequest("test")).actionGet());
} }

View file

@ -754,11 +754,9 @@ public class DataStreamIT extends ESIntegTestCase {
); );
// Searching the data stream directly should return all hits: // Searching the data stream directly should return all hits:
SearchResponse searchResponse = client().prepareSearch("logs-foobar").get(); assertSearchHits(client().prepareSearch("logs-foobar"), "1", "2");
assertSearchHits(searchResponse, "1", "2");
// Search the alias should only return document 2, because it matches with the defined filter in the alias: // Search the alias should only return document 2, because it matches with the defined filter in the alias:
searchResponse = client().prepareSearch("foo").get(); assertSearchHits(client().prepareSearch("foo"), "2");
assertSearchHits(searchResponse, "2");
// Update alias: // Update alias:
addAction = new AliasActions(AliasActions.Type.ADD).index(dataStreamName) addAction = new AliasActions(AliasActions.Type.ADD).index(dataStreamName)
@ -786,11 +784,9 @@ public class DataStreamIT extends ESIntegTestCase {
); );
// Searching the data stream directly should return all hits: // Searching the data stream directly should return all hits:
searchResponse = client().prepareSearch("logs-foobar").get(); assertSearchHits(client().prepareSearch("logs-foobar"), "1", "2");
assertSearchHits(searchResponse, "1", "2");
// Search the alias should only return document 1, because it matches with the defined filter in the alias: // Search the alias should only return document 1, because it matches with the defined filter in the alias:
searchResponse = client().prepareSearch("foo").get(); assertSearchHits(client().prepareSearch("foo"), "1");
assertSearchHits(searchResponse, "1");
} }
public void testSearchFilteredAndUnfilteredAlias() throws Exception { public void testSearchFilteredAndUnfilteredAlias() throws Exception {
@ -833,11 +829,9 @@ public class DataStreamIT extends ESIntegTestCase {
); );
// Searching the filtered and unfiltered aliases should return all results (unfiltered): // Searching the filtered and unfiltered aliases should return all results (unfiltered):
SearchResponse searchResponse = client().prepareSearch("foo", "bar").get(); assertSearchHits(client().prepareSearch("foo", "bar"), "1", "2");
assertSearchHits(searchResponse, "1", "2");
// Searching the data stream name and the filtered alias should return all results (unfiltered): // Searching the data stream name and the filtered alias should return all results (unfiltered):
searchResponse = client().prepareSearch("foo", dataStreamName).get(); assertSearchHits(client().prepareSearch("foo", dataStreamName), "1", "2");
assertSearchHits(searchResponse, "1", "2");
} }
public void testRandomDataSteamAliasesUpdate() throws Exception { public void testRandomDataSteamAliasesUpdate() throws Exception {

View file

@ -43,6 +43,7 @@ import static org.elasticsearch.search.aggregations.AggregationBuilders.histogra
import static org.elasticsearch.search.aggregations.AggregationBuilders.sum; import static org.elasticsearch.search.aggregations.AggregationBuilders.sum;
import static org.elasticsearch.search.aggregations.PipelineAggregatorBuilders.bucketScript; import static org.elasticsearch.search.aggregations.PipelineAggregatorBuilders.bucketScript;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse;
import static org.elasticsearch.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.xcontent.XContentFactory.jsonBuilder;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalTo;
@ -129,8 +130,7 @@ public class MoreExpressionIT extends ESIntegTestCase {
score = ScoreFunctionBuilders.scriptFunction(new Script(ScriptType.INLINE, "expression", "1 / _score", Collections.emptyMap())); score = ScoreFunctionBuilders.scriptFunction(new Script(ScriptType.INLINE, "expression", "1 / _score", Collections.emptyMap()));
req.addAggregation(AggregationBuilders.max("max_score").script((score).getScript())); req.addAggregation(AggregationBuilders.max("max_score").script((score).getScript()));
req.setSearchType(SearchType.DFS_QUERY_THEN_FETCH); // make sure DF is consistent req.setSearchType(SearchType.DFS_QUERY_THEN_FETCH); // make sure DF is consistent
rsp = req.get(); assertNoFailures(req);
assertSearchResponse(rsp);
} }
public void testDateMethods() throws Exception { public void testDateMethods() throws Exception {

View file

@ -247,14 +247,10 @@ public class ChildQuerySearchIT extends ParentChildTestCase {
for (int i = 1; i <= 10; i++) { for (int i = 1; i <= 10; i++) {
logger.info("Round {}", i); logger.info("Round {}", i);
SearchResponse searchResponse = client().prepareSearch("test") assertNoFailures(
.setQuery(constantScoreQuery(hasChildQuery("child", matchAllQuery(), ScoreMode.Max))) client().prepareSearch("test").setQuery(constantScoreQuery(hasChildQuery("child", matchAllQuery(), ScoreMode.Max)))
.get(); );
assertNoFailures(searchResponse); assertNoFailures(client().prepareSearch("test").setQuery(constantScoreQuery(hasParentQuery("parent", matchAllQuery(), true))));
searchResponse = client().prepareSearch("test")
.setQuery(constantScoreQuery(hasParentQuery("parent", matchAllQuery(), true)))
.get();
assertNoFailures(searchResponse);
} }
} }
@ -471,18 +467,17 @@ public class ChildQuerySearchIT extends ParentChildTestCase {
refresh(); refresh();
SearchResponse searchResponse = client().prepareSearch("test") assertNoFailures(
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH) client().prepareSearch("test")
.setQuery(boolQuery().mustNot(hasChildQuery("child", boolQuery().should(queryStringQuery("c_field:*")), ScoreMode.None))) .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
.get(); .setQuery(boolQuery().mustNot(hasChildQuery("child", boolQuery().should(queryStringQuery("c_field:*")), ScoreMode.None)))
assertNoFailures(searchResponse); );
searchResponse = client().prepareSearch("test") assertNoFailures(
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH) client().prepareSearch("test")
.setQuery(boolQuery().mustNot(hasParentQuery("parent", boolQuery().should(queryStringQuery("p_field:*")), false))) .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
.execute() .setQuery(boolQuery().mustNot(hasParentQuery("parent", boolQuery().should(queryStringQuery("p_field:*")), false)))
.actionGet(); );
assertNoFailures(searchResponse);
} }
public void testHasChildAndHasParentFailWhenSomeSegmentsDontContainAnyParentOrChildDocs() throws Exception { public void testHasChildAndHasParentFailWhenSomeSegmentsDontContainAnyParentOrChildDocs() throws Exception {
@ -1711,15 +1706,15 @@ public class ChildQuerySearchIT extends ParentChildTestCase {
refresh(); refresh();
// make sure that when we explicitly set a type, the inner query is executed in the context of the child type instead // make sure that when we explicitly set a type, the inner query is executed in the context of the child type instead
SearchResponse searchResponse = client().prepareSearch("test") assertSearchHits(
.setQuery(hasChildQuery("child-type", new IdsQueryBuilder().addIds("child-id"), ScoreMode.None)) client().prepareSearch("test").setQuery(hasChildQuery("child-type", new IdsQueryBuilder().addIds("child-id"), ScoreMode.None)),
.get(); "parent-id"
assertSearchHits(searchResponse, "parent-id"); );
// make sure that when we explicitly set a type, the inner query is executed in the context of the parent type instead // make sure that when we explicitly set a type, the inner query is executed in the context of the parent type instead
searchResponse = client().prepareSearch("test") assertSearchHits(
.setQuery(hasParentQuery("parent-type", new IdsQueryBuilder().addIds("parent-id"), false)) client().prepareSearch("test").setQuery(hasParentQuery("parent-type", new IdsQueryBuilder().addIds("parent-id"), false)),
.get(); "child-id"
assertSearchHits(searchResponse, "child-id"); );
} }
public void testHighlightersIgnoreParentChild() throws IOException { public void testHighlightersIgnoreParentChild() throws IOException {

View file

@ -676,19 +676,19 @@ public class InnerHitsIT extends ParentChildTestCase {
containsString("the inner hit definition's [_name]'s from + size must be less than or equal to: [100] but was [110]") containsString("the inner hit definition's [_name]'s from + size must be less than or equal to: [100] but was [110]")
); );
updateIndexSettings(Settings.builder().put(IndexSettings.MAX_INNER_RESULT_WINDOW_SETTING.getKey(), 110), "index1"); updateIndexSettings(Settings.builder().put(IndexSettings.MAX_INNER_RESULT_WINDOW_SETTING.getKey(), 110), "index1");
response = client().prepareSearch("index1") assertNoFailures(
.setQuery( client().prepareSearch("index1")
hasChildQuery("child_type", matchAllQuery(), ScoreMode.None).ignoreUnmapped(true) .setQuery(
.innerHit(new InnerHitBuilder().setFrom(100).setSize(10).setName("_name")) hasChildQuery("child_type", matchAllQuery(), ScoreMode.None).ignoreUnmapped(true)
) .innerHit(new InnerHitBuilder().setFrom(100).setSize(10).setName("_name"))
.get(); )
assertNoFailures(response); );
response = client().prepareSearch("index1") assertNoFailures(
.setQuery( client().prepareSearch("index1")
hasChildQuery("child_type", matchAllQuery(), ScoreMode.None).ignoreUnmapped(true) .setQuery(
.innerHit(new InnerHitBuilder().setFrom(10).setSize(100).setName("_name")) hasChildQuery("child_type", matchAllQuery(), ScoreMode.None).ignoreUnmapped(true)
) .innerHit(new InnerHitBuilder().setFrom(10).setSize(100).setName("_name"))
.get(); )
assertNoFailures(response); );
} }
} }

View file

@ -81,7 +81,6 @@ import static org.elasticsearch.core.TimeValue.timeValueSeconds;
import static org.elasticsearch.http.HttpTransportSettings.SETTING_HTTP_MAX_HEADER_SIZE; import static org.elasticsearch.http.HttpTransportSettings.SETTING_HTTP_MAX_HEADER_SIZE;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertFutureThrows; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertFutureThrows;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse;
import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.empty;
@ -359,7 +358,7 @@ public class TasksIT extends ESIntegTestCase {
headers.put(Task.X_OPAQUE_ID_HTTP_HEADER, "my_id"); headers.put(Task.X_OPAQUE_ID_HTTP_HEADER, "my_id");
headers.put("Foo-Header", "bar"); headers.put("Foo-Header", "bar");
headers.put("Custom-Task-Header", "my_value"); headers.put("Custom-Task-Header", "my_value");
assertSearchResponse(client().filterWithHeader(headers).prepareSearch("test").setQuery(QueryBuilders.matchAllQuery()).get()); assertNoFailures(client().filterWithHeader(headers).prepareSearch("test").setQuery(QueryBuilders.matchAllQuery()));
// the search operation should produce one main task // the search operation should produce one main task
List<TaskInfo> mainTask = findEvents(SearchAction.NAME, Tuple::v1); List<TaskInfo> mainTask = findEvents(SearchAction.NAME, Tuple::v1);

View file

@ -48,12 +48,12 @@ public class DeleteIndexBlocksIT extends ESIntegTestCase {
refresh(); refresh();
try { try {
updateIndexSettings(Settings.builder().put(IndexMetadata.SETTING_READ_ONLY_ALLOW_DELETE, true), "test"); updateIndexSettings(Settings.builder().put(IndexMetadata.SETTING_READ_ONLY_ALLOW_DELETE, true), "test");
assertSearchHits(client().prepareSearch().get(), "1"); assertSearchHits(client().prepareSearch(), "1");
assertBlocked( assertBlocked(
client().prepareIndex().setIndex("test").setId("2").setSource("foo", "bar"), client().prepareIndex().setIndex("test").setId("2").setSource("foo", "bar"),
IndexMetadata.INDEX_READ_ONLY_ALLOW_DELETE_BLOCK IndexMetadata.INDEX_READ_ONLY_ALLOW_DELETE_BLOCK
); );
assertSearchHits(client().prepareSearch().get(), "1"); assertSearchHits(client().prepareSearch(), "1");
assertAcked(indicesAdmin().prepareDelete("test")); assertAcked(indicesAdmin().prepareDelete("test"));
} finally { } finally {
Settings settings = Settings.builder().putNull(IndexMetadata.SETTING_READ_ONLY_ALLOW_DELETE).build(); Settings settings = Settings.builder().putNull(IndexMetadata.SETTING_READ_ONLY_ALLOW_DELETE).build();
@ -92,7 +92,7 @@ public class DeleteIndexBlocksIT extends ESIntegTestCase {
refresh(); refresh();
try { try {
updateClusterSettings(Settings.builder().put(Metadata.SETTING_READ_ONLY_ALLOW_DELETE_SETTING.getKey(), true)); updateClusterSettings(Settings.builder().put(Metadata.SETTING_READ_ONLY_ALLOW_DELETE_SETTING.getKey(), true));
assertSearchHits(client().prepareSearch().get(), "1"); assertSearchHits(client().prepareSearch(), "1");
assertBlocked( assertBlocked(
client().prepareIndex().setIndex("test").setId("2").setSource("foo", "bar"), client().prepareIndex().setIndex("test").setId("2").setSource("foo", "bar"),
Metadata.CLUSTER_READ_ONLY_ALLOW_DELETE_BLOCK Metadata.CLUSTER_READ_ONLY_ALLOW_DELETE_BLOCK
@ -101,7 +101,7 @@ public class DeleteIndexBlocksIT extends ESIntegTestCase {
indicesAdmin().prepareUpdateSettings("test").setSettings(Settings.builder().put("index.number_of_replicas", 2)), indicesAdmin().prepareUpdateSettings("test").setSettings(Settings.builder().put("index.number_of_replicas", 2)),
Metadata.CLUSTER_READ_ONLY_ALLOW_DELETE_BLOCK Metadata.CLUSTER_READ_ONLY_ALLOW_DELETE_BLOCK
); );
assertSearchHits(client().prepareSearch().get(), "1"); assertSearchHits(client().prepareSearch(), "1");
assertAcked(indicesAdmin().prepareDelete("test")); assertAcked(indicesAdmin().prepareDelete("test"));
} finally { } finally {
updateClusterSettings(Settings.builder().putNull(Metadata.SETTING_READ_ONLY_ALLOW_DELETE_SETTING.getKey())); updateClusterSettings(Settings.builder().putNull(Metadata.SETTING_READ_ONLY_ALLOW_DELETE_SETTING.getKey()));

View file

@ -195,7 +195,7 @@ public class MockDiskUsagesIT extends ESIntegTestCase {
} }
client().prepareIndex("test").setId("1").setSource("foo", "bar").setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE).get(); client().prepareIndex("test").setId("1").setSource("foo", "bar").setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE).get();
assertSearchHits(client().prepareSearch("test").get(), "1"); assertSearchHits(client().prepareSearch("test"), "1");
// Move all nodes above the low watermark so no shard movement can occur, and at least one node above the flood stage watermark so // Move all nodes above the low watermark so no shard movement can occur, and at least one node above the flood stage watermark so
// the index is blocked // the index is blocked
@ -221,7 +221,7 @@ public class MockDiskUsagesIT extends ESIntegTestCase {
client().prepareIndex().setIndex("test").setId("2").setSource("foo", "bar"), client().prepareIndex().setIndex("test").setId("2").setSource("foo", "bar"),
IndexMetadata.INDEX_READ_ONLY_ALLOW_DELETE_BLOCK IndexMetadata.INDEX_READ_ONLY_ALLOW_DELETE_BLOCK
); );
assertSearchHits(client().prepareSearch("test").get(), "1"); assertSearchHits(client().prepareSearch("test"), "1");
logger.info("--> index is confirmed read-only, releasing disk space"); logger.info("--> index is confirmed read-only, releasing disk space");
@ -240,7 +240,7 @@ public class MockDiskUsagesIT extends ESIntegTestCase {
throw new AssertionError("retrying", e); throw new AssertionError("retrying", e);
} }
}); });
assertSearchHits(client().prepareSearch("test").get(), "1", "3"); assertSearchHits(client().prepareSearch("test"), "1", "3");
} }
public void testOnlyMovesEnoughShardsToDropBelowHighWatermark() throws Exception { public void testOnlyMovesEnoughShardsToDropBelowHighWatermark() throws Exception {

View file

@ -63,13 +63,13 @@ public class WaitUntilRefreshIT extends ESIntegTestCase {
.get(); .get();
assertEquals(RestStatus.CREATED, index.status()); assertEquals(RestStatus.CREATED, index.status());
assertFalse("request shouldn't have forced a refresh", index.forcedRefresh()); assertFalse("request shouldn't have forced a refresh", index.forcedRefresh());
assertSearchHits(client().prepareSearch("test").setQuery(matchQuery("foo", "bar")).get(), "1"); assertSearchHits(client().prepareSearch("test").setQuery(matchQuery("foo", "bar")), "1");
} }
public void testDelete() throws InterruptedException, ExecutionException { public void testDelete() throws InterruptedException, ExecutionException {
// Index normally // Index normally
indexRandom(true, client().prepareIndex("test").setId("1").setSource("foo", "bar")); indexRandom(true, client().prepareIndex("test").setId("1").setSource("foo", "bar"));
assertSearchHits(client().prepareSearch("test").setQuery(matchQuery("foo", "bar")).get(), "1"); assertSearchHits(client().prepareSearch("test").setQuery(matchQuery("foo", "bar")), "1");
// Now delete with blockUntilRefresh // Now delete with blockUntilRefresh
DeleteResponse delete = client().prepareDelete("test", "1").setRefreshPolicy(RefreshPolicy.WAIT_UNTIL).get(); DeleteResponse delete = client().prepareDelete("test", "1").setRefreshPolicy(RefreshPolicy.WAIT_UNTIL).get();
@ -81,7 +81,7 @@ public class WaitUntilRefreshIT extends ESIntegTestCase {
public void testUpdate() throws InterruptedException, ExecutionException { public void testUpdate() throws InterruptedException, ExecutionException {
// Index normally // Index normally
indexRandom(true, client().prepareIndex("test").setId("1").setSource("foo", "bar")); indexRandom(true, client().prepareIndex("test").setId("1").setSource("foo", "bar"));
assertSearchHits(client().prepareSearch("test").setQuery(matchQuery("foo", "bar")).get(), "1"); assertSearchHits(client().prepareSearch("test").setQuery(matchQuery("foo", "bar")), "1");
// Update with RefreshPolicy.WAIT_UNTIL // Update with RefreshPolicy.WAIT_UNTIL
UpdateResponse update = client().prepareUpdate("test", "1") UpdateResponse update = client().prepareUpdate("test", "1")
@ -90,7 +90,7 @@ public class WaitUntilRefreshIT extends ESIntegTestCase {
.get(); .get();
assertEquals(2, update.getVersion()); assertEquals(2, update.getVersion());
assertFalse("request shouldn't have forced a refresh", update.forcedRefresh()); assertFalse("request shouldn't have forced a refresh", update.forcedRefresh());
assertSearchHits(client().prepareSearch("test").setQuery(matchQuery("foo", "baz")).get(), "1"); assertSearchHits(client().prepareSearch("test").setQuery(matchQuery("foo", "baz")), "1");
// Upsert with RefreshPolicy.WAIT_UNTIL // Upsert with RefreshPolicy.WAIT_UNTIL
update = client().prepareUpdate("test", "2") update = client().prepareUpdate("test", "2")
@ -100,7 +100,7 @@ public class WaitUntilRefreshIT extends ESIntegTestCase {
.get(); .get();
assertEquals(1, update.getVersion()); assertEquals(1, update.getVersion());
assertFalse("request shouldn't have forced a refresh", update.forcedRefresh()); assertFalse("request shouldn't have forced a refresh", update.forcedRefresh());
assertSearchHits(client().prepareSearch("test").setQuery(matchQuery("foo", "cat")).get(), "2"); assertSearchHits(client().prepareSearch("test").setQuery(matchQuery("foo", "cat")), "2");
// Update-becomes-delete with RefreshPolicy.WAIT_UNTIL // Update-becomes-delete with RefreshPolicy.WAIT_UNTIL
update = client().prepareUpdate("test", "2") update = client().prepareUpdate("test", "2")
@ -117,13 +117,13 @@ public class WaitUntilRefreshIT extends ESIntegTestCase {
BulkRequestBuilder bulk = client().prepareBulk().setRefreshPolicy(RefreshPolicy.WAIT_UNTIL); BulkRequestBuilder bulk = client().prepareBulk().setRefreshPolicy(RefreshPolicy.WAIT_UNTIL);
bulk.add(client().prepareIndex("test").setId("1").setSource("foo", "bar")); bulk.add(client().prepareIndex("test").setId("1").setSource("foo", "bar"));
assertBulkSuccess(bulk.get()); assertBulkSuccess(bulk.get());
assertSearchHits(client().prepareSearch("test").setQuery(matchQuery("foo", "bar")).get(), "1"); assertSearchHits(client().prepareSearch("test").setQuery(matchQuery("foo", "bar")), "1");
// Update by bulk with RefreshPolicy.WAIT_UNTIL // Update by bulk with RefreshPolicy.WAIT_UNTIL
bulk = client().prepareBulk().setRefreshPolicy(RefreshPolicy.WAIT_UNTIL); bulk = client().prepareBulk().setRefreshPolicy(RefreshPolicy.WAIT_UNTIL);
bulk.add(client().prepareUpdate("test", "1").setDoc(Requests.INDEX_CONTENT_TYPE, "foo", "baz")); bulk.add(client().prepareUpdate("test", "1").setDoc(Requests.INDEX_CONTENT_TYPE, "foo", "baz"));
assertBulkSuccess(bulk.get()); assertBulkSuccess(bulk.get());
assertSearchHits(client().prepareSearch("test").setQuery(matchQuery("foo", "baz")).get(), "1"); assertSearchHits(client().prepareSearch("test").setQuery(matchQuery("foo", "baz")), "1");
// Delete by bulk with RefreshPolicy.WAIT_UNTIL // Delete by bulk with RefreshPolicy.WAIT_UNTIL
bulk = client().prepareBulk().setRefreshPolicy(RefreshPolicy.WAIT_UNTIL); bulk = client().prepareBulk().setRefreshPolicy(RefreshPolicy.WAIT_UNTIL);
@ -153,7 +153,7 @@ public class WaitUntilRefreshIT extends ESIntegTestCase {
} }
assertEquals(RestStatus.CREATED, index.get().status()); assertEquals(RestStatus.CREATED, index.get().status());
assertFalse("request shouldn't have forced a refresh", index.get().forcedRefresh()); assertFalse("request shouldn't have forced a refresh", index.get().forcedRefresh());
assertSearchHits(client().prepareSearch("test").setQuery(matchQuery("foo", "bar")).get(), "1"); assertSearchHits(client().prepareSearch("test").setQuery(matchQuery("foo", "bar")), "1");
} }
private void assertBulkSuccess(BulkResponse response) { private void assertBulkSuccess(BulkResponse response) {

View file

@ -371,14 +371,18 @@ public class DynamicMappingIT extends ESIntegTestCase {
final BulkResponse bulkResponse = client().bulk(bulkRequest).actionGet(); final BulkResponse bulkResponse = client().bulk(bulkRequest).actionGet();
assertFalse(bulkResponse.hasFailures()); assertFalse(bulkResponse.hasFailures());
SearchResponse searchResponse = client().prepareSearch("test") assertSearchHits(
.setQuery(new GeoBoundingBoxQueryBuilder("location").setCorners(new GeoPoint(42, -72), new GeoPoint(40, -74))) client().prepareSearch("test")
.get(); .setQuery(new GeoBoundingBoxQueryBuilder("location").setCorners(new GeoPoint(42, -72), new GeoPoint(40, -74))),
assertSearchHits(searchResponse, "1", "2", "4"); "1",
searchResponse = client().prepareSearch("test") "2",
.setQuery(new GeoBoundingBoxQueryBuilder("address.location").setCorners(new GeoPoint(42, -72), new GeoPoint(40, -74))) "4"
.get(); );
assertSearchHits(searchResponse, "3"); assertSearchHits(
client().prepareSearch("test")
.setQuery(new GeoBoundingBoxQueryBuilder("address.location").setCorners(new GeoPoint(42, -72), new GeoPoint(40, -74))),
"3"
);
} }
public void testBulkRequestWithNotFoundDynamicTemplate() throws Exception { public void testBulkRequestWithNotFoundDynamicTemplate() throws Exception {

View file

@ -82,7 +82,7 @@ import java.util.concurrent.atomic.AtomicReference;
import static org.elasticsearch.cluster.metadata.IndexMetadata.SETTING_NUMBER_OF_REPLICAS; import static org.elasticsearch.cluster.metadata.IndexMetadata.SETTING_NUMBER_OF_REPLICAS;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAllSuccessful; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAllSuccessful;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures;
import static org.elasticsearch.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.xcontent.XContentFactory.jsonBuilder;
import static org.hamcrest.Matchers.emptyCollectionOf; import static org.hamcrest.Matchers.emptyCollectionOf;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalTo;
@ -1163,8 +1163,8 @@ public class IndexStatsIT extends ESIntegTestCase {
// the query cache has an optimization that disables it automatically if there is contention, // the query cache has an optimization that disables it automatically if there is contention,
// so we run it in an assertBusy block which should eventually succeed // so we run it in an assertBusy block which should eventually succeed
assertBusy(() -> { assertBusy(() -> {
assertSearchResponse( assertNoFailures(
client().prepareSearch("index").setQuery(QueryBuilders.constantScoreQuery(QueryBuilders.matchQuery("foo", "baz"))).get() client().prepareSearch("index").setQuery(QueryBuilders.constantScoreQuery(QueryBuilders.matchQuery("foo", "baz")))
); );
IndicesStatsResponse stats = indicesAdmin().prepareStats("index").setQueryCache(true).get(); IndicesStatsResponse stats = indicesAdmin().prepareStats("index").setQueryCache(true).get();
assertCumulativeQueryCacheStats(stats); assertCumulativeQueryCacheStats(stats);
@ -1174,8 +1174,8 @@ public class IndexStatsIT extends ESIntegTestCase {
}); });
assertBusy(() -> { assertBusy(() -> {
assertSearchResponse( assertNoFailures(
client().prepareSearch("index").setQuery(QueryBuilders.constantScoreQuery(QueryBuilders.matchQuery("foo", "baz"))).get() client().prepareSearch("index").setQuery(QueryBuilders.constantScoreQuery(QueryBuilders.matchQuery("foo", "baz")))
); );
IndicesStatsResponse stats = indicesAdmin().prepareStats("index").setQueryCache(true).get(); IndicesStatsResponse stats = indicesAdmin().prepareStats("index").setQueryCache(true).get();
assertCumulativeQueryCacheStats(stats); assertCumulativeQueryCacheStats(stats);
@ -1224,8 +1224,8 @@ public class IndexStatsIT extends ESIntegTestCase {
); );
assertBusy(() -> { assertBusy(() -> {
assertSearchResponse( assertNoFailures(
client().prepareSearch("index").setQuery(QueryBuilders.constantScoreQuery(QueryBuilders.matchQuery("foo", "baz"))).get() client().prepareSearch("index").setQuery(QueryBuilders.constantScoreQuery(QueryBuilders.matchQuery("foo", "baz")))
); );
IndicesStatsResponse stats = indicesAdmin().prepareStats("index").setQueryCache(true).get(); IndicesStatsResponse stats = indicesAdmin().prepareStats("index").setQueryCache(true).get();
assertCumulativeQueryCacheStats(stats); assertCumulativeQueryCacheStats(stats);

View file

@ -485,7 +485,7 @@ public class RelocationIT extends ESIntegTestCase {
for (int i = 0; i < searchThreads.length; i++) { for (int i = 0; i < searchThreads.length; i++) {
searchThreads[i] = new Thread(() -> { searchThreads[i] = new Thread(() -> {
while (stopped.get() == false) { while (stopped.get() == false) {
assertNoFailures(client().prepareSearch("test").setRequestCache(false).get()); assertNoFailures(client().prepareSearch("test").setRequestCache(false));
} }
}); });
searchThreads[i].start(); searchThreads[i].start();

View file

@ -995,28 +995,29 @@ public class TopHitsIT extends ESIntegTestCase {
Settings.builder().put(IndexSettings.MAX_INNER_RESULT_WINDOW_SETTING.getKey(), ArrayUtil.MAX_ARRAY_LENGTH), Settings.builder().put(IndexSettings.MAX_INNER_RESULT_WINDOW_SETTING.getKey(), ArrayUtil.MAX_ARRAY_LENGTH),
"idx" "idx"
); );
SearchResponse response = client().prepareSearch("idx") assertNoFailures(
.addAggregation( client().prepareSearch("idx")
terms("terms").executionHint(randomExecutionHint()) .addAggregation(
.field(TERMS_AGGS_FIELD) terms("terms").executionHint(randomExecutionHint())
.subAggregation( .field(TERMS_AGGS_FIELD)
topHits("hits").size(ArrayUtil.MAX_ARRAY_LENGTH - 1).sort(SortBuilders.fieldSort(SORT_FIELD).order(SortOrder.DESC)) .subAggregation(
) topHits("hits").size(ArrayUtil.MAX_ARRAY_LENGTH - 1)
) .sort(SortBuilders.fieldSort(SORT_FIELD).order(SortOrder.DESC))
.get(); )
assertNoFailures(response); )
);
updateIndexSettings(Settings.builder().putNull(IndexSettings.MAX_INNER_RESULT_WINDOW_SETTING.getKey()), "idx"); updateIndexSettings(Settings.builder().putNull(IndexSettings.MAX_INNER_RESULT_WINDOW_SETTING.getKey()), "idx");
} }
public void testTooHighResultWindow() throws Exception { public void testTooHighResultWindow() throws Exception {
SearchResponse response = client().prepareSearch("idx") assertNoFailures(
.addAggregation( client().prepareSearch("idx")
terms("terms").executionHint(randomExecutionHint()) .addAggregation(
.field(TERMS_AGGS_FIELD) terms("terms").executionHint(randomExecutionHint())
.subAggregation(topHits("hits").from(50).size(10).sort(SortBuilders.fieldSort(SORT_FIELD).order(SortOrder.DESC))) .field(TERMS_AGGS_FIELD)
) .subAggregation(topHits("hits").from(50).size(10).sort(SortBuilders.fieldSort(SORT_FIELD).order(SortOrder.DESC)))
.get(); )
assertNoFailures(response); );
Exception e = expectThrows( Exception e = expectThrows(
SearchPhaseExecutionException.class, SearchPhaseExecutionException.class,
@ -1048,22 +1049,22 @@ public class TopHitsIT extends ESIntegTestCase {
); );
updateIndexSettings(Settings.builder().put(IndexSettings.MAX_INNER_RESULT_WINDOW_SETTING.getKey(), 110), "idx"); updateIndexSettings(Settings.builder().put(IndexSettings.MAX_INNER_RESULT_WINDOW_SETTING.getKey(), 110), "idx");
response = client().prepareSearch("idx") assertNoFailures(
.addAggregation( client().prepareSearch("idx")
terms("terms").executionHint(randomExecutionHint()) .addAggregation(
.field(TERMS_AGGS_FIELD) terms("terms").executionHint(randomExecutionHint())
.subAggregation(topHits("hits").from(100).size(10).sort(SortBuilders.fieldSort(SORT_FIELD).order(SortOrder.DESC))) .field(TERMS_AGGS_FIELD)
) .subAggregation(topHits("hits").from(100).size(10).sort(SortBuilders.fieldSort(SORT_FIELD).order(SortOrder.DESC)))
.get(); )
assertNoFailures(response); );
response = client().prepareSearch("idx") assertNoFailures(
.addAggregation( client().prepareSearch("idx")
terms("terms").executionHint(randomExecutionHint()) .addAggregation(
.field(TERMS_AGGS_FIELD) terms("terms").executionHint(randomExecutionHint())
.subAggregation(topHits("hits").from(10).size(100).sort(SortBuilders.fieldSort(SORT_FIELD).order(SortOrder.DESC))) .field(TERMS_AGGS_FIELD)
) .subAggregation(topHits("hits").from(10).size(100).sort(SortBuilders.fieldSort(SORT_FIELD).order(SortOrder.DESC)))
.get(); )
assertNoFailures(response); );
updateIndexSettings(Settings.builder().putNull(IndexSettings.MAX_INNER_RESULT_WINDOW_SETTING.getKey()), "idx"); updateIndexSettings(Settings.builder().putNull(IndexSettings.MAX_INNER_RESULT_WINDOW_SETTING.getKey()), "idx");
} }

View file

@ -1006,22 +1006,22 @@ public class InnerHitsIT extends ESIntegTestCase {
); );
updateIndexSettings(Settings.builder().put(IndexSettings.MAX_INNER_RESULT_WINDOW_SETTING.getKey(), 110), "index2"); updateIndexSettings(Settings.builder().put(IndexSettings.MAX_INNER_RESULT_WINDOW_SETTING.getKey(), 110), "index2");
response = client().prepareSearch("index2") assertNoFailures(
.setQuery( client().prepareSearch("index2")
nestedQuery("nested", matchQuery("nested.field", "value1"), ScoreMode.Avg).innerHit( .setQuery(
new InnerHitBuilder().setFrom(100).setSize(10).setName("_name") nestedQuery("nested", matchQuery("nested.field", "value1"), ScoreMode.Avg).innerHit(
new InnerHitBuilder().setFrom(100).setSize(10).setName("_name")
)
) )
) );
.get(); assertNoFailures(
assertNoFailures(response); client().prepareSearch("index2")
response = client().prepareSearch("index2") .setQuery(
.setQuery( nestedQuery("nested", matchQuery("nested.field", "value1"), ScoreMode.Avg).innerHit(
nestedQuery("nested", matchQuery("nested.field", "value1"), ScoreMode.Avg).innerHit( new InnerHitBuilder().setFrom(10).setSize(100).setName("_name")
new InnerHitBuilder().setFrom(10).setSize(100).setName("_name") )
) )
) );
.get();
assertNoFailures(response);
} }
} }

View file

@ -1539,11 +1539,11 @@ public class HighlighterSearchIT extends ESIntegTestCase {
} }
indexRandom(true, indexRequestBuilders); indexRandom(true, indexRequestBuilders);
SearchResponse search = client().prepareSearch() assertNoFailures(
.setQuery(matchPhraseQuery("title", "this is a test")) client().prepareSearch()
.highlighter(new HighlightBuilder().field("title", 50, 1, 10)) .setQuery(matchPhraseQuery("title", "this is a test"))
.get(); .highlighter(new HighlightBuilder().field("title", 50, 1, 10))
assertNoFailures(search); );
assertFailures( assertFailures(
client().prepareSearch() client().prepareSearch()
@ -1560,7 +1560,6 @@ public class HighlighterSearchIT extends ESIntegTestCase {
client().prepareSearch() client().prepareSearch()
.setQuery(matchPhraseQuery("title", "this is a test")) .setQuery(matchPhraseQuery("title", "this is a test"))
.highlighter(new HighlightBuilder().field("tit*", 50, 1, 10).highlighterType("fvh")) .highlighter(new HighlightBuilder().field("tit*", 50, 1, 10).highlighterType("fvh"))
.get()
); );
} }
@ -2656,11 +2655,9 @@ public class HighlighterSearchIT extends ESIntegTestCase {
} }
indexRandom(true, indexRequestBuilders); indexRandom(true, indexRequestBuilders);
SearchResponse search = client().prepareSearch() assertNoFailures(
.setQuery(matchQuery("title", "this is a test")) client().prepareSearch().setQuery(matchQuery("title", "this is a test")).highlighter(new HighlightBuilder().field("title"))
.highlighter(new HighlightBuilder().field("title")) );
.get();
assertNoFailures(search);
} }
public void testPostingsHighlighterBoostingQuery() throws IOException { public void testPostingsHighlighterBoostingQuery() throws IOException {

View file

@ -53,39 +53,45 @@ public class FunctionScoreFieldValueIT extends ESIntegTestCase {
refresh(); refresh();
// document 2 scores higher because 17 > 5 // document 2 scores higher because 17 > 5
SearchResponse response = client().prepareSearch("test") assertOrderedSearchHits(
.setExplain(randomBoolean()) client().prepareSearch("test")
.setQuery(functionScoreQuery(simpleQueryStringQuery("foo"), fieldValueFactorFunction("test"))) .setExplain(randomBoolean())
.get(); .setQuery(functionScoreQuery(simpleQueryStringQuery("foo"), fieldValueFactorFunction("test"))),
assertOrderedSearchHits(response, "2", "1"); "2",
"1"
);
// try again, but this time explicitly use the do-nothing modifier // try again, but this time explicitly use the do-nothing modifier
response = client().prepareSearch("test") assertOrderedSearchHits(
.setExplain(randomBoolean()) client().prepareSearch("test")
.setQuery( .setExplain(randomBoolean())
functionScoreQuery( .setQuery(
simpleQueryStringQuery("foo"), functionScoreQuery(
fieldValueFactorFunction("test").modifier(FieldValueFactorFunction.Modifier.NONE) simpleQueryStringQuery("foo"),
) fieldValueFactorFunction("test").modifier(FieldValueFactorFunction.Modifier.NONE)
) )
.get(); ),
assertOrderedSearchHits(response, "2", "1"); "2",
"1"
);
// document 1 scores higher because 1/5 > 1/17 // document 1 scores higher because 1/5 > 1/17
response = client().prepareSearch("test") assertOrderedSearchHits(
.setExplain(randomBoolean()) client().prepareSearch("test")
.setQuery( .setExplain(randomBoolean())
functionScoreQuery( .setQuery(
simpleQueryStringQuery("foo"), functionScoreQuery(
fieldValueFactorFunction("test").modifier(FieldValueFactorFunction.Modifier.RECIPROCAL) simpleQueryStringQuery("foo"),
) fieldValueFactorFunction("test").modifier(FieldValueFactorFunction.Modifier.RECIPROCAL)
) )
.get(); ),
assertOrderedSearchHits(response, "1", "2"); "1",
"2"
);
// doc 3 doesn't have a "test" field, so an exception will be thrown // doc 3 doesn't have a "test" field, so an exception will be thrown
try { try {
response = client().prepareSearch("test") SearchResponse response = client().prepareSearch("test")
.setExplain(randomBoolean()) .setExplain(randomBoolean())
.setQuery(functionScoreQuery(matchAllQuery(), fieldValueFactorFunction("test"))) .setQuery(functionScoreQuery(matchAllQuery(), fieldValueFactorFunction("test")))
.get(); .get();
@ -95,19 +101,22 @@ public class FunctionScoreFieldValueIT extends ESIntegTestCase {
} }
// doc 3 doesn't have a "test" field but we're defaulting it to 100 so it should be last // doc 3 doesn't have a "test" field but we're defaulting it to 100 so it should be last
response = client().prepareSearch("test") assertOrderedSearchHits(
.setExplain(randomBoolean()) client().prepareSearch("test")
.setQuery( .setExplain(randomBoolean())
functionScoreQuery( .setQuery(
matchAllQuery(), functionScoreQuery(
fieldValueFactorFunction("test").modifier(FieldValueFactorFunction.Modifier.RECIPROCAL).missing(100) matchAllQuery(),
) fieldValueFactorFunction("test").modifier(FieldValueFactorFunction.Modifier.RECIPROCAL).missing(100)
) )
.get(); ),
assertOrderedSearchHits(response, "1", "2", "3"); "1",
"2",
"3"
);
// field is not mapped but we're defaulting it to 100 so all documents should have the same score // field is not mapped but we're defaulting it to 100 so all documents should have the same score
response = client().prepareSearch("test") SearchResponse response = client().prepareSearch("test")
.setExplain(randomBoolean()) .setExplain(randomBoolean())
.setQuery( .setQuery(
functionScoreQuery( functionScoreQuery(

View file

@ -317,14 +317,12 @@ public class RandomScoreFunctionIT extends ESIntegTestCase {
client().prepareSearch() client().prepareSearch()
.setSize(docCount) // get all docs otherwise we are prone to tie-breaking .setSize(docCount) // get all docs otherwise we are prone to tie-breaking
.setQuery(functionScoreQuery(matchAllQuery(), randomFunction().seed(randomInt()).setField(SeqNoFieldMapper.NAME))) .setQuery(functionScoreQuery(matchAllQuery(), randomFunction().seed(randomInt()).setField(SeqNoFieldMapper.NAME)))
.get()
); );
assertNoFailures( assertNoFailures(
client().prepareSearch() client().prepareSearch()
.setSize(docCount) // get all docs otherwise we are prone to tie-breaking .setSize(docCount) // get all docs otherwise we are prone to tie-breaking
.setQuery(functionScoreQuery(matchAllQuery(), randomFunction().seed(randomLong()).setField(SeqNoFieldMapper.NAME))) .setQuery(functionScoreQuery(matchAllQuery(), randomFunction().seed(randomLong()).setField(SeqNoFieldMapper.NAME)))
.get()
); );
assertNoFailures( assertNoFailures(
@ -336,7 +334,6 @@ public class RandomScoreFunctionIT extends ESIntegTestCase {
randomFunction().seed(randomRealisticUnicodeOfLengthBetween(10, 20)).setField(SeqNoFieldMapper.NAME) randomFunction().seed(randomRealisticUnicodeOfLengthBetween(10, 20)).setField(SeqNoFieldMapper.NAME)
) )
) )
.get()
); );
} }

View file

@ -47,7 +47,6 @@ import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSear
import static org.elasticsearch.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.xcontent.XContentFactory.jsonBuilder;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.notNullValue;
public class MoreLikeThisIT extends ESIntegTestCase { public class MoreLikeThisIT extends ESIntegTestCase {
@ -289,14 +288,8 @@ public class MoreLikeThisIT extends ESIntegTestCase {
indicesAdmin().prepareRefresh("foo").get(); indicesAdmin().prepareRefresh("foo").get();
assertThat(ensureGreen(), equalTo(ClusterHealthStatus.GREEN)); assertThat(ensureGreen(), equalTo(ClusterHealthStatus.GREEN));
SearchResponse response = client().prepareSearch() assertNoFailures(client().prepareSearch().setQuery(new MoreLikeThisQueryBuilder(null, new Item[] { new Item("foo", "1") })));
.setQuery(new MoreLikeThisQueryBuilder(null, new Item[] { new Item("foo", "1") })) assertNoFailures(client().prepareSearch().setQuery(new MoreLikeThisQueryBuilder(null, new Item[] { new Item("foo", "1") })));
.get();
assertNoFailures(response);
assertThat(response, notNullValue());
response = client().prepareSearch().setQuery(new MoreLikeThisQueryBuilder(null, new Item[] { new Item("foo", "1") })).get();
assertNoFailures(response);
assertThat(response, notNullValue());
} }
// Issue #2489 // Issue #2489
@ -311,11 +304,9 @@ public class MoreLikeThisIT extends ESIntegTestCase {
.get(); .get();
indicesAdmin().prepareRefresh("foo").get(); indicesAdmin().prepareRefresh("foo").get();
SearchResponse response = client().prepareSearch() assertNoFailures(
.setQuery(new MoreLikeThisQueryBuilder(null, new Item[] { new Item("foo", "1").routing("2") })) client().prepareSearch().setQuery(new MoreLikeThisQueryBuilder(null, new Item[] { new Item("foo", "1").routing("2") }))
.get(); );
assertNoFailures(response);
assertThat(response, notNullValue());
} }
// Issue #3039 // Issue #3039
@ -329,11 +320,9 @@ public class MoreLikeThisIT extends ESIntegTestCase {
.setRouting("4000") .setRouting("4000")
.get(); .get();
indicesAdmin().prepareRefresh("foo").get(); indicesAdmin().prepareRefresh("foo").get();
SearchResponse response = client().prepareSearch() assertNoFailures(
.setQuery(new MoreLikeThisQueryBuilder(null, new Item[] { new Item("foo", "1").routing("4000") })) client().prepareSearch().setQuery(new MoreLikeThisQueryBuilder(null, new Item[] { new Item("foo", "1").routing("4000") }))
.get(); );
assertNoFailures(response);
assertThat(response, notNullValue());
} }
// Issue #3252 // Issue #3252
@ -520,35 +509,40 @@ public class MoreLikeThisIT extends ESIntegTestCase {
indicesAdmin().refresh(new RefreshRequest()).actionGet(); indicesAdmin().refresh(new RefreshRequest()).actionGet();
logger.info("Running More Like This with include true"); logger.info("Running More Like This with include true");
SearchResponse response = client().prepareSearch() assertOrderedSearchHits(
.setQuery( client().prepareSearch()
new MoreLikeThisQueryBuilder(null, new Item[] { new Item("test", "1") }).minTermFreq(1) .setQuery(
.minDocFreq(1) new MoreLikeThisQueryBuilder(null, new Item[] { new Item("test", "1") }).minTermFreq(1)
.include(true) .minDocFreq(1)
.minimumShouldMatch("0%") .include(true)
) .minimumShouldMatch("0%")
.get(); ),
assertOrderedSearchHits(response, "1", "2"); "1",
"2"
);
response = client().prepareSearch() assertOrderedSearchHits(
.setQuery( client().prepareSearch()
new MoreLikeThisQueryBuilder(null, new Item[] { new Item("test", "2") }).minTermFreq(1) .setQuery(
.minDocFreq(1) new MoreLikeThisQueryBuilder(null, new Item[] { new Item("test", "2") }).minTermFreq(1)
.include(true) .minDocFreq(1)
.minimumShouldMatch("0%") .include(true)
) .minimumShouldMatch("0%")
.get(); ),
assertOrderedSearchHits(response, "2", "1"); "2",
"1"
);
logger.info("Running More Like This with include false"); logger.info("Running More Like This with include false");
response = client().prepareSearch() assertSearchHits(
.setQuery( client().prepareSearch()
new MoreLikeThisQueryBuilder(null, new Item[] { new Item("test", "1") }).minTermFreq(1) .setQuery(
.minDocFreq(1) new MoreLikeThisQueryBuilder(null, new Item[] { new Item("test", "1") }).minTermFreq(1)
.minimumShouldMatch("0%") .minDocFreq(1)
) .minimumShouldMatch("0%")
.get(); ),
assertSearchHits(response, "2"); "2"
);
} }
public void testSimpleMoreLikeThisIds() throws Exception { public void testSimpleMoreLikeThisIds() throws Exception {

View file

@ -9,8 +9,6 @@
package org.elasticsearch.search.nested; package org.elasticsearch.search.nested;
import org.apache.lucene.search.join.ScoreMode; import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.WriteRequest; import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.ConstantScoreQueryBuilder; import org.elasticsearch.index.query.ConstantScoreQueryBuilder;
@ -113,8 +111,6 @@ public class NestedWithMinScoreIT extends ESIntegTestCase {
if (randomBoolean()) { if (randomBoolean()) {
source.trackTotalHitsUpTo(randomBoolean() ? Integer.MAX_VALUE : randomIntBetween(1, 1000)); source.trackTotalHitsUpTo(randomBoolean() ? Integer.MAX_VALUE : randomIntBetween(1, 1000));
} }
SearchRequest searchRequest = new SearchRequest("test").source(source); ElasticsearchAssertions.assertSearchHits(client().prepareSearch("test").setSource(source), "d1");
final SearchResponse searchResponse = client().search(searchRequest).actionGet();
ElasticsearchAssertions.assertSearchHits(searchResponse, "d1");
} }
} }

View file

@ -30,6 +30,7 @@ import static java.util.Collections.emptyMap;
import static java.util.Collections.singletonMap; import static java.util.Collections.singletonMap;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse;
public class ExistsIT extends ESIntegTestCase { public class ExistsIT extends ESIntegTestCase {
@ -37,10 +38,8 @@ public class ExistsIT extends ESIntegTestCase {
// TODO: move this to a unit test somewhere... // TODO: move this to a unit test somewhere...
public void testEmptyIndex() throws Exception { public void testEmptyIndex() throws Exception {
createIndex("test"); createIndex("test");
SearchResponse resp = client().prepareSearch("test").setQuery(QueryBuilders.existsQuery("foo")).get(); assertNoFailures(client().prepareSearch("test").setQuery(QueryBuilders.existsQuery("foo")));
assertSearchResponse(resp); assertNoFailures(client().prepareSearch("test").setQuery(QueryBuilders.boolQuery().mustNot(QueryBuilders.existsQuery("foo"))));
resp = client().prepareSearch("test").setQuery(QueryBuilders.boolQuery().mustNot(QueryBuilders.existsQuery("foo"))).get();
assertSearchResponse(resp);
} }
public void testExists() throws Exception { public void testExists() throws Exception {

View file

@ -136,10 +136,7 @@ public class ScriptScoreQueryIT extends ESIntegTestCase {
// Execute with search.allow_expensive_queries = null => default value = true => success // Execute with search.allow_expensive_queries = null => default value = true => success
Script script = new Script(ScriptType.INLINE, CustomScriptPlugin.NAME, "doc['field2'].value * param1", Map.of("param1", 0.1)); Script script = new Script(ScriptType.INLINE, CustomScriptPlugin.NAME, "doc['field2'].value * param1", Map.of("param1", 0.1));
SearchResponse resp = client().prepareSearch("test-index") assertNoFailures(client().prepareSearch("test-index").setQuery(scriptScoreQuery(matchQuery("field1", "text0"), script)));
.setQuery(scriptScoreQuery(matchQuery("field1", "text0"), script))
.get();
assertNoFailures(resp);
// Set search.allow_expensive_queries to "false" => assert failure // Set search.allow_expensive_queries to "false" => assert failure
updateClusterSettings(Settings.builder().put("search.allow_expensive_queries", false)); updateClusterSettings(Settings.builder().put("search.allow_expensive_queries", false));
@ -155,8 +152,7 @@ public class ScriptScoreQueryIT extends ESIntegTestCase {
// Set search.allow_expensive_queries to "true" => success // Set search.allow_expensive_queries to "true" => success
updateClusterSettings(Settings.builder().put("search.allow_expensive_queries", true)); updateClusterSettings(Settings.builder().put("search.allow_expensive_queries", true));
resp = client().prepareSearch("test-index").setQuery(scriptScoreQuery(matchQuery("field1", "text0"), script)).get(); assertNoFailures(client().prepareSearch("test-index").setQuery(scriptScoreQuery(matchQuery("field1", "text0"), script)));
assertNoFailures(resp);
} finally { } finally {
updateClusterSettings(Settings.builder().put("search.allow_expensive_queries", (String) null)); updateClusterSettings(Settings.builder().put("search.allow_expensive_queries", (String) null));
} }

View file

@ -1474,25 +1474,27 @@ public class SearchQueryIT extends ESIntegTestCase {
.get(); .get();
refresh(); refresh();
SearchResponse response = client().prepareSearch("test") assertNoFailures(
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH) client().prepareSearch("test")
.setQuery( .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
boolQuery().must(termQuery("online", true)) .setQuery(
.must( boolQuery().must(termQuery("online", true))
boolQuery().should( .must(
boolQuery().must(rangeQuery("ts").lt(System.currentTimeMillis() - (15 * 1000))).must(termQuery("type", "bs")) boolQuery().should(
) boolQuery().must(rangeQuery("ts").lt(System.currentTimeMillis() - (15 * 1000)))
.should( .must(termQuery("type", "bs"))
boolQuery().must(rangeQuery("ts").lt(System.currentTimeMillis() - (15 * 1000))).must(termQuery("type", "s"))
) )
) .should(
) boolQuery().must(rangeQuery("ts").lt(System.currentTimeMillis() - (15 * 1000)))
.setVersion(true) .must(termQuery("type", "s"))
.setFrom(0) )
.setSize(100) )
.setExplain(true) )
.get(); .setVersion(true)
assertNoFailures(response); .setFrom(0)
.setSize(100)
.setExplain(true)
);
} }
public void testMultiFieldQueryString() { public void testMultiFieldQueryString() {

View file

@ -224,8 +224,7 @@ public class ScriptQuerySearchIT extends ESIntegTestCase {
// Execute with search.allow_expensive_queries = null => default value = false => success // Execute with search.allow_expensive_queries = null => default value = false => success
Script script = new Script(ScriptType.INLINE, CustomScriptPlugin.NAME, "doc['num1'].value > 1", Collections.emptyMap()); Script script = new Script(ScriptType.INLINE, CustomScriptPlugin.NAME, "doc['num1'].value > 1", Collections.emptyMap());
SearchResponse resp = client().prepareSearch("test-index").setQuery(scriptQuery(script)).get(); assertNoFailures(client().prepareSearch("test-index").setQuery(scriptQuery(script)));
assertNoFailures(resp);
updateClusterSettings(Settings.builder().put("search.allow_expensive_queries", false)); updateClusterSettings(Settings.builder().put("search.allow_expensive_queries", false));
@ -241,8 +240,7 @@ public class ScriptQuerySearchIT extends ESIntegTestCase {
// Set search.allow_expensive_queries to "true" => success // Set search.allow_expensive_queries to "true" => success
updateClusterSettings(Settings.builder().put("search.allow_expensive_queries", true)); updateClusterSettings(Settings.builder().put("search.allow_expensive_queries", true));
resp = client().prepareSearch("test-index").setQuery(scriptQuery(script)).get(); assertNoFailures(client().prepareSearch("test-index").setQuery(scriptQuery(script)));
assertNoFailures(resp);
} finally { } finally {
updateClusterSettings(Settings.builder().put("search.allow_expensive_queries", (String) null)); updateClusterSettings(Settings.builder().put("search.allow_expensive_queries", (String) null));
} }

View file

@ -269,7 +269,7 @@ public class SearchAfterIT extends ESIntegTestCase {
.addSort(SortBuilders.fieldSort("end_date").setFormat("epoch_millis")) .addSort(SortBuilders.fieldSort("end_date").setFormat("epoch_millis"))
.searchAfter(new Object[] { "21/02/2016", 1748390400000L }) .searchAfter(new Object[] { "21/02/2016", 1748390400000L })
.setSize(2); .setSize(2);
assertNoFailures(searchRequest.get()); assertNoFailures(searchRequest);
searchRequest = client().prepareSearch("test") searchRequest = client().prepareSearch("test")
.addSort(SortBuilders.fieldSort("start_date").setFormat("dd/MM/yyyy")) .addSort(SortBuilders.fieldSort("start_date").setFormat("dd/MM/yyyy"))

View file

@ -1071,33 +1071,29 @@ public class FieldSortIT extends ESIntegTestCase {
} }
} }
SearchResponse searchResponse = client().prepareSearch() assertNoFailures(client().prepareSearch().setQuery(matchAllQuery()).addSort(SortBuilders.fieldSort("kkk").unmappedType("keyword")));
.setQuery(matchAllQuery())
.addSort(SortBuilders.fieldSort("kkk").unmappedType("keyword"))
.get();
assertNoFailures(searchResponse);
// nested field // nested field
searchResponse = client().prepareSearch() assertNoFailures(
.setQuery(matchAllQuery()) client().prepareSearch()
.addSort( .setQuery(matchAllQuery())
SortBuilders.fieldSort("nested.foo") .addSort(
.unmappedType("keyword") SortBuilders.fieldSort("nested.foo")
.setNestedSort(new NestedSortBuilder("nested").setNestedSort(new NestedSortBuilder("nested.foo"))) .unmappedType("keyword")
) .setNestedSort(new NestedSortBuilder("nested").setNestedSort(new NestedSortBuilder("nested.foo")))
.get(); )
assertNoFailures(searchResponse); );
// nestedQuery // nestedQuery
searchResponse = client().prepareSearch() assertNoFailures(
.setQuery(matchAllQuery()) client().prepareSearch()
.addSort( .setQuery(matchAllQuery())
SortBuilders.fieldSort("nested.foo") .addSort(
.unmappedType("keyword") SortBuilders.fieldSort("nested.foo")
.setNestedSort(new NestedSortBuilder("nested").setFilter(QueryBuilders.termQuery("nested.foo", "abc"))) .unmappedType("keyword")
) .setNestedSort(new NestedSortBuilder("nested").setFilter(QueryBuilders.termQuery("nested.foo", "abc")))
.get(); )
assertNoFailures(searchResponse); );
} }
public void testSortMVField() throws Exception { public void testSortMVField() throws Exception {

View file

@ -368,25 +368,26 @@ public class GeoDistanceSortBuilderIT extends ESIntegTestCase {
client().prepareIndex("test2").setSource() client().prepareIndex("test2").setSource()
); );
SearchResponse resp = client().prepareSearch("test1", "test2")
.addSort(fieldSort("str_field").order(SortOrder.ASC).unmappedType("keyword"))
.addSort(fieldSort("str_field2").order(SortOrder.DESC).unmappedType("keyword"))
.get();
assertSortValues(resp, new Object[] { "bcd", null }, new Object[] { null, null });
resp = client().prepareSearch("test1", "test2")
.addSort(fieldSort("long_field").order(SortOrder.ASC).unmappedType("long"))
.addSort(fieldSort("long_field2").order(SortOrder.DESC).unmappedType("long"))
.get();
assertSortValues(resp, new Object[] { 3L, Long.MIN_VALUE }, new Object[] { Long.MAX_VALUE, Long.MIN_VALUE });
resp = client().prepareSearch("test1", "test2")
.addSort(fieldSort("double_field").order(SortOrder.ASC).unmappedType("double"))
.addSort(fieldSort("double_field2").order(SortOrder.DESC).unmappedType("double"))
.get();
assertSortValues( assertSortValues(
resp, client().prepareSearch("test1", "test2")
.addSort(fieldSort("str_field").order(SortOrder.ASC).unmappedType("keyword"))
.addSort(fieldSort("str_field2").order(SortOrder.DESC).unmappedType("keyword")),
new Object[] { "bcd", null },
new Object[] { null, null }
);
assertSortValues(
client().prepareSearch("test1", "test2")
.addSort(fieldSort("long_field").order(SortOrder.ASC).unmappedType("long"))
.addSort(fieldSort("long_field2").order(SortOrder.DESC).unmappedType("long")),
new Object[] { 3L, Long.MIN_VALUE },
new Object[] { Long.MAX_VALUE, Long.MIN_VALUE }
);
assertSortValues(
client().prepareSearch("test1", "test2")
.addSort(fieldSort("double_field").order(SortOrder.ASC).unmappedType("double"))
.addSort(fieldSort("double_field2").order(SortOrder.DESC).unmappedType("double")),
new Object[] { 0.65, Double.NEGATIVE_INFINITY }, new Object[] { 0.65, Double.NEGATIVE_INFINITY },
new Object[] { Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY } new Object[] { Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY }
); );

View file

@ -443,11 +443,8 @@ public class SimpleSortIT extends ESIntegTestCase {
refresh(); refresh();
Script sortScript = new Script(ScriptType.INLINE, CustomScriptPlugin.NAME, "\u0027\u0027", Collections.emptyMap()); Script sortScript = new Script(ScriptType.INLINE, CustomScriptPlugin.NAME, "\u0027\u0027", Collections.emptyMap());
SearchResponse searchResponse = client().prepareSearch() assertNoFailures(
.setQuery(matchAllQuery()) client().prepareSearch().setQuery(matchAllQuery()).addSort(scriptSort(sortScript, ScriptSortType.STRING)).setSize(10)
.addSort(scriptSort(sortScript, ScriptSortType.STRING)) );
.setSize(10)
.get();
assertNoFailures(searchResponse);
} }
} }

View file

@ -63,8 +63,8 @@ public class SimpleThreadPoolIT extends ESIntegTestCase {
indexRandom(true, builders); indexRandom(true, builders);
int numSearches = randomIntBetween(2, 100); int numSearches = randomIntBetween(2, 100);
for (int i = 0; i < numSearches; i++) { for (int i = 0; i < numSearches; i++) {
assertNoFailures(client().prepareSearch("idx").setQuery(QueryBuilders.termQuery("str_value", "s" + i)).get()); assertNoFailures(client().prepareSearch("idx").setQuery(QueryBuilders.termQuery("str_value", "s" + i)));
assertNoFailures(client().prepareSearch("idx").setQuery(QueryBuilders.termQuery("l_value", i)).get()); assertNoFailures(client().prepareSearch("idx").setQuery(QueryBuilders.termQuery("l_value", i)));
} }
Set<String> threadNames = new HashSet<>(); Set<String> threadNames = new HashSet<>();
for (long l : threadBean.getAllThreadIds()) { for (long l : threadBean.getAllThreadIds()) {

View file

@ -1108,11 +1108,12 @@ public class SearchServiceTests extends ESSingleNodeTestCase {
Index index = resolveIndex("throttled_threadpool_index"); Index index = resolveIndex("throttled_threadpool_index");
assertTrue(service.getIndicesService().indexServiceSafe(index).getIndexSettings().isSearchThrottled()); assertTrue(service.getIndicesService().indexServiceSafe(index).getIndexSettings().isSearchThrottled());
client().prepareIndex("throttled_threadpool_index").setId("1").setSource("field", "value").setRefreshPolicy(IMMEDIATE).get(); client().prepareIndex("throttled_threadpool_index").setId("1").setSource("field", "value").setRefreshPolicy(IMMEDIATE).get();
SearchResponse searchResponse = client().prepareSearch("throttled_threadpool_index") assertSearchHits(
.setIndicesOptions(IndicesOptions.STRICT_EXPAND_OPEN_FORBID_CLOSED) client().prepareSearch("throttled_threadpool_index")
.setSize(1) .setIndicesOptions(IndicesOptions.STRICT_EXPAND_OPEN_FORBID_CLOSED)
.get(); .setSize(1),
assertSearchHits(searchResponse, "1"); "1"
);
// we add a search action listener in a plugin above to assert that this is actually used // we add a search action listener in a plugin above to assert that this is actually used
client().execute( client().execute(
InternalOrPrivateSettingsPlugin.UpdateInternalOrPrivateAction.INSTANCE, InternalOrPrivateSettingsPlugin.UpdateInternalOrPrivateAction.INSTANCE,

View file

@ -227,6 +227,15 @@ public class ElasticsearchAssertions {
assertThat(searchResponse.getHits().getHits(), emptyArray()); assertThat(searchResponse.getHits().getHits(), emptyArray());
} }
public static void assertSearchHits(SearchRequestBuilder searchRequestBuilder, String... ids) {
var res = searchRequestBuilder.get();
try {
assertSearchHits(res, ids);
} finally {
res.decRef();
}
}
public static void assertSearchHits(SearchResponse searchResponse, String... ids) { public static void assertSearchHits(SearchResponse searchResponse, String... ids) {
assertThat( assertThat(
"Incorrect SearchHit ids. " + formatShardStatus(searchResponse), "Incorrect SearchHit ids. " + formatShardStatus(searchResponse),
@ -235,13 +244,27 @@ public class ElasticsearchAssertions {
); );
} }
public static void assertSortValues(SearchResponse searchResponse, Object[]... sortValues) { public static void assertSortValues(SearchRequestBuilder searchRequestBuilder, Object[]... sortValues) {
assertSearchResponse(searchResponse); var searchResponse = searchRequestBuilder.get();
SearchHit[] hits = searchResponse.getHits().getHits(); try {
assertEquals(sortValues.length, hits.length); assertSearchResponse(searchResponse);
for (int i = 0; i < sortValues.length; ++i) { SearchHit[] hits = searchResponse.getHits().getHits();
final Object[] hitsSortValues = hits[i].getSortValues(); assertEquals(sortValues.length, hits.length);
assertArrayEquals("Offset " + i + ", id " + hits[i].getId(), sortValues[i], hitsSortValues); for (int i = 0; i < sortValues.length; ++i) {
final Object[] hitsSortValues = hits[i].getSortValues();
assertArrayEquals("Offset " + i + ", id " + hits[i].getId(), sortValues[i], hitsSortValues);
}
} finally {
searchResponse.decRef();
}
}
public static void assertOrderedSearchHits(SearchRequestBuilder searchRequestBuilder, String... ids) {
var res = searchRequestBuilder.get();
try {
assertOrderedSearchHits(res, ids);
} finally {
res.decRef();
} }
} }
@ -296,6 +319,15 @@ public class ElasticsearchAssertions {
assertThat(searchResponse.getHits().getAt(number - 1), matcher); assertThat(searchResponse.getHits().getAt(number - 1), matcher);
} }
public static void assertNoFailures(SearchRequestBuilder searchRequestBuilder) {
var res = searchRequestBuilder.get();
try {
assertNoFailures(res);
} finally {
res.decRef();
}
}
public static void assertNoFailures(SearchResponse searchResponse) { public static void assertNoFailures(SearchResponse searchResponse) {
assertThat( assertThat(
"Unexpected ShardFailures: " + Arrays.toString(searchResponse.getShardFailures()), "Unexpected ShardFailures: " + Arrays.toString(searchResponse.getShardFailures()),