Search in sources :

Example 96 with SearchHits

use of org.elasticsearch.search.SearchHits in project elasticsearch by elastic.

the class InnerHitsIT method testRoyals.

public void testRoyals() throws Exception {
    assertAcked(prepareCreate("royals").addMapping("king").addMapping("prince", "_parent", "type=king").addMapping("duke", "_parent", "type=prince").addMapping("earl", "_parent", "type=duke").addMapping("baron", "_parent", "type=earl"));
    List<IndexRequestBuilder> requests = new ArrayList<>();
    requests.add(client().prepareIndex("royals", "king", "king").setSource("{}", XContentType.JSON));
    requests.add(client().prepareIndex("royals", "prince", "prince").setParent("king").setSource("{}", XContentType.JSON));
    requests.add(client().prepareIndex("royals", "duke", "duke").setParent("prince").setRouting("king").setSource("{}", XContentType.JSON));
    requests.add(client().prepareIndex("royals", "earl", "earl1").setParent("duke").setRouting("king").setSource("{}", XContentType.JSON));
    requests.add(client().prepareIndex("royals", "earl", "earl2").setParent("duke").setRouting("king").setSource("{}", XContentType.JSON));
    requests.add(client().prepareIndex("royals", "earl", "earl3").setParent("duke").setRouting("king").setSource("{}", XContentType.JSON));
    requests.add(client().prepareIndex("royals", "earl", "earl4").setParent("duke").setRouting("king").setSource("{}", XContentType.JSON));
    requests.add(client().prepareIndex("royals", "baron", "baron1").setParent("earl1").setRouting("king").setSource("{}", XContentType.JSON));
    requests.add(client().prepareIndex("royals", "baron", "baron2").setParent("earl2").setRouting("king").setSource("{}", XContentType.JSON));
    requests.add(client().prepareIndex("royals", "baron", "baron3").setParent("earl3").setRouting("king").setSource("{}", XContentType.JSON));
    requests.add(client().prepareIndex("royals", "baron", "baron4").setParent("earl4").setRouting("king").setSource("{}", XContentType.JSON));
    indexRandom(true, requests);
    SearchResponse response = client().prepareSearch("royals").setTypes("duke").setQuery(boolQuery().filter(hasParentQuery("prince", hasParentQuery("king", matchAllQuery(), false).innerHit(new InnerHitBuilder().setName("kings"), false), false).innerHit(new InnerHitBuilder().setName("princes"), false)).filter(hasChildQuery("earl", hasChildQuery("baron", matchAllQuery(), ScoreMode.None).innerHit(new InnerHitBuilder().setName("barons"), false), ScoreMode.None).innerHit(new InnerHitBuilder().addSort(SortBuilders.fieldSort("_uid").order(SortOrder.ASC)).setName("earls").setSize(4), false))).get();
    assertHitCount(response, 1);
    assertThat(response.getHits().getAt(0).getId(), equalTo("duke"));
    SearchHits innerHits = response.getHits().getAt(0).getInnerHits().get("earls");
    assertThat(innerHits.getTotalHits(), equalTo(4L));
    assertThat(innerHits.getAt(0).getId(), equalTo("earl1"));
    assertThat(innerHits.getAt(1).getId(), equalTo("earl2"));
    assertThat(innerHits.getAt(2).getId(), equalTo("earl3"));
    assertThat(innerHits.getAt(3).getId(), equalTo("earl4"));
    SearchHits innerInnerHits = innerHits.getAt(0).getInnerHits().get("barons");
    assertThat(innerInnerHits.getTotalHits(), equalTo(1L));
    assertThat(innerInnerHits.getAt(0).getId(), equalTo("baron1"));
    innerInnerHits = innerHits.getAt(1).getInnerHits().get("barons");
    assertThat(innerInnerHits.getTotalHits(), equalTo(1L));
    assertThat(innerInnerHits.getAt(0).getId(), equalTo("baron2"));
    innerInnerHits = innerHits.getAt(2).getInnerHits().get("barons");
    assertThat(innerInnerHits.getTotalHits(), equalTo(1L));
    assertThat(innerInnerHits.getAt(0).getId(), equalTo("baron3"));
    innerInnerHits = innerHits.getAt(3).getInnerHits().get("barons");
    assertThat(innerInnerHits.getTotalHits(), equalTo(1L));
    assertThat(innerInnerHits.getAt(0).getId(), equalTo("baron4"));
    innerHits = response.getHits().getAt(0).getInnerHits().get("princes");
    assertThat(innerHits.getTotalHits(), equalTo(1L));
    assertThat(innerHits.getAt(0).getId(), equalTo("prince"));
    innerInnerHits = innerHits.getAt(0).getInnerHits().get("kings");
    assertThat(innerInnerHits.getTotalHits(), equalTo(1L));
    assertThat(innerInnerHits.getAt(0).getId(), equalTo("king"));
}
Also used : IndexRequestBuilder(org.elasticsearch.action.index.IndexRequestBuilder) ArrayList(java.util.ArrayList) InnerHitBuilder(org.elasticsearch.index.query.InnerHitBuilder) SearchHits(org.elasticsearch.search.SearchHits) SearchResponse(org.elasticsearch.action.search.SearchResponse)

Example 97 with SearchHits

use of org.elasticsearch.search.SearchHits in project elasticsearch by elastic.

the class InnerHitsIT method testInnerHitsWithObjectFieldThatHasANestedField.

public void testInnerHitsWithObjectFieldThatHasANestedField() throws Exception {
    assertAcked(prepareCreate("articles").addMapping("article", jsonBuilder().startObject().startObject("properties").startObject("comments").field("type", "object").startObject("properties").startObject("messages").field("type", "nested").endObject().endObject().endObject().endObject().endObject()));
    List<IndexRequestBuilder> requests = new ArrayList<>();
    requests.add(client().prepareIndex("articles", "article", "1").setSource(jsonBuilder().startObject().field("title", "quick brown fox").startObject("comments").startArray("messages").startObject().field("message", "fox eat quick").endObject().startObject().field("message", "bear eat quick").endObject().endArray().endObject().endObject()));
    indexRandom(true, requests);
    SearchResponse response = client().prepareSearch("articles").setQuery(nestedQuery("comments.messages", matchQuery("comments.messages.message", "fox"), ScoreMode.Avg).innerHit(new InnerHitBuilder(), false)).get();
    assertNoFailures(response);
    assertHitCount(response, 1);
    SearchHit hit = response.getHits().getAt(0);
    assertThat(hit.getId(), equalTo("1"));
    SearchHits messages = hit.getInnerHits().get("comments.messages");
    assertThat(messages.getTotalHits(), equalTo(1L));
    assertThat(messages.getAt(0).getId(), equalTo("1"));
    assertThat(messages.getAt(0).getNestedIdentity().getField().string(), equalTo("comments.messages"));
    assertThat(messages.getAt(0).getNestedIdentity().getOffset(), equalTo(0));
    assertThat(messages.getAt(0).getNestedIdentity().getChild(), nullValue());
    response = client().prepareSearch("articles").setQuery(nestedQuery("comments.messages", matchQuery("comments.messages.message", "bear"), ScoreMode.Avg).innerHit(new InnerHitBuilder(), false)).get();
    assertNoFailures(response);
    assertHitCount(response, 1);
    hit = response.getHits().getAt(0);
    assertThat(hit.getId(), equalTo("1"));
    messages = hit.getInnerHits().get("comments.messages");
    assertThat(messages.getTotalHits(), equalTo(1L));
    assertThat(messages.getAt(0).getId(), equalTo("1"));
    assertThat(messages.getAt(0).getNestedIdentity().getField().string(), equalTo("comments.messages"));
    assertThat(messages.getAt(0).getNestedIdentity().getOffset(), equalTo(1));
    assertThat(messages.getAt(0).getNestedIdentity().getChild(), nullValue());
    // index the message in an object form instead of an array
    requests = new ArrayList<>();
    requests.add(client().prepareIndex("articles", "article", "1").setSource(jsonBuilder().startObject().field("title", "quick brown fox").startObject("comments").startObject("messages").field("message", "fox eat quick").endObject().endObject().endObject()));
    indexRandom(true, requests);
    response = client().prepareSearch("articles").setQuery(nestedQuery("comments.messages", matchQuery("comments.messages.message", "fox"), ScoreMode.Avg).innerHit(new InnerHitBuilder(), false)).get();
    assertNoFailures(response);
    assertHitCount(response, 1);
    hit = response.getHits().getAt(0);
    ;
    assertThat(hit.getId(), equalTo("1"));
    messages = hit.getInnerHits().get("comments.messages");
    assertThat(messages.getTotalHits(), equalTo(1L));
    assertThat(messages.getAt(0).getId(), equalTo("1"));
    assertThat(messages.getAt(0).getNestedIdentity().getField().string(), equalTo("comments.messages"));
    assertThat(messages.getAt(0).getNestedIdentity().getOffset(), equalTo(0));
    assertThat(messages.getAt(0).getNestedIdentity().getChild(), nullValue());
}
Also used : IndexRequestBuilder(org.elasticsearch.action.index.IndexRequestBuilder) SearchHit(org.elasticsearch.search.SearchHit) ElasticsearchAssertions.assertSearchHit(org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchHit) ArrayList(java.util.ArrayList) InnerHitBuilder(org.elasticsearch.index.query.InnerHitBuilder) SearchHits(org.elasticsearch.search.SearchHits) SearchResponse(org.elasticsearch.action.search.SearchResponse)

Example 98 with SearchHits

use of org.elasticsearch.search.SearchHits in project elasticsearch by elastic.

the class InternalTopHitsTests method createTestInstance.

@Override
protected InternalTopHits createTestInstance(String name, List<PipelineAggregator> pipelineAggregators, Map<String, Object> metaData) {
    int from = 0;
    int requestedSize = between(1, 40);
    int actualSize = between(0, requestedSize);
    float maxScore = Float.MIN_VALUE;
    ScoreDoc[] scoreDocs = new ScoreDoc[actualSize];
    SearchHit[] hits = new SearchHit[actualSize];
    Set<Integer> usedDocIds = new HashSet<>();
    for (int i = 0; i < actualSize; i++) {
        float score = randomFloat();
        maxScore = max(maxScore, score);
        int docId = randomValueOtherThanMany(usedDocIds::contains, () -> between(0, IndexWriter.MAX_DOCS));
        usedDocIds.add(docId);
        Map<String, SearchHitField> searchHitFields = new HashMap<>();
        if (testInstancesLookSortedByField) {
            Object[] fields = new Object[testInstancesSortFields.length];
            for (int f = 0; f < testInstancesSortFields.length; f++) {
                fields[f] = randomOfType(testInstancesSortFields[f].getType());
            }
            scoreDocs[i] = new FieldDoc(docId, score, fields);
        } else {
            scoreDocs[i] = new ScoreDoc(docId, score);
        }
        hits[i] = new SearchHit(docId, Integer.toString(i), new Text("test"), searchHitFields);
        hits[i].score(score);
    }
    int totalHits = between(actualSize, 500000);
    SearchHits searchHits = new SearchHits(hits, totalHits, maxScore);
    TopDocs topDocs;
    Arrays.sort(scoreDocs, scoreDocComparator());
    if (testInstancesLookSortedByField) {
        topDocs = new TopFieldDocs(totalHits, scoreDocs, testInstancesSortFields, maxScore);
    } else {
        topDocs = new TopDocs(totalHits, scoreDocs, maxScore);
    }
    return new InternalTopHits(name, from, requestedSize, topDocs, searchHits, pipelineAggregators, metaData);
}
Also used : SearchHit(org.elasticsearch.search.SearchHit) FieldDoc(org.apache.lucene.search.FieldDoc) HashMap(java.util.HashMap) TopFieldDocs(org.apache.lucene.search.TopFieldDocs) Text(org.elasticsearch.common.text.Text) ScoreDoc(org.apache.lucene.search.ScoreDoc) TopDocs(org.apache.lucene.search.TopDocs) SearchHitField(org.elasticsearch.search.SearchHitField) SearchHits(org.elasticsearch.search.SearchHits) HashSet(java.util.HashSet)

Example 99 with SearchHits

use of org.elasticsearch.search.SearchHits in project elasticsearch by elastic.

the class InternalTopHitsTests method assertReduced.

@Override
protected void assertReduced(InternalTopHits reduced, List<InternalTopHits> inputs) {
    SearchHits actualHits = reduced.getHits();
    List<Tuple<ScoreDoc, SearchHit>> allHits = new ArrayList<>();
    float maxScore = Float.MIN_VALUE;
    long totalHits = 0;
    for (int input = 0; input < inputs.size(); input++) {
        SearchHits internalHits = inputs.get(input).getHits();
        totalHits += internalHits.getTotalHits();
        maxScore = max(maxScore, internalHits.getMaxScore());
        for (int i = 0; i < internalHits.internalHits().length; i++) {
            ScoreDoc doc = inputs.get(input).getTopDocs().scoreDocs[i];
            if (testInstancesLookSortedByField) {
                doc = new FieldDoc(doc.doc, doc.score, ((FieldDoc) doc).fields, input);
            } else {
                doc = new ScoreDoc(doc.doc, doc.score, input);
            }
            allHits.add(new Tuple<>(doc, internalHits.internalHits()[i]));
        }
    }
    allHits.sort(comparing(Tuple::v1, scoreDocComparator()));
    SearchHit[] expectedHitsHits = new SearchHit[min(inputs.get(0).getSize(), allHits.size())];
    for (int i = 0; i < expectedHitsHits.length; i++) {
        expectedHitsHits[i] = allHits.get(i).v2();
    }
    SearchHits expectedHits = new SearchHits(expectedHitsHits, totalHits, maxScore);
    assertEqualsWithErrorMessageFromXContent(expectedHits, actualHits);
}
Also used : FieldDoc(org.apache.lucene.search.FieldDoc) SearchHit(org.elasticsearch.search.SearchHit) ArrayList(java.util.ArrayList) SearchHits(org.elasticsearch.search.SearchHits) Tuple(org.elasticsearch.common.collect.Tuple) ScoreDoc(org.apache.lucene.search.ScoreDoc)

Example 100 with SearchHits

use of org.elasticsearch.search.SearchHits in project elasticsearch by elastic.

the class TopHitsAggregatorTests method testNoResults.

public void testNoResults() throws Exception {
    TopHits result = (TopHits) testCase(new MatchNoDocsQuery(), topHits("_name").sort("string", SortOrder.DESC));
    SearchHits searchHits = ((TopHits) result).getHits();
    assertEquals(0L, searchHits.getTotalHits());
}
Also used : MatchNoDocsQuery(org.apache.lucene.search.MatchNoDocsQuery) SearchHits(org.elasticsearch.search.SearchHits)

Aggregations

SearchHits (org.elasticsearch.search.SearchHits)137 SearchResponse (org.elasticsearch.action.search.SearchResponse)93 SearchHit (org.elasticsearch.search.SearchHit)86 ArrayList (java.util.ArrayList)45 SearchRequestBuilder (org.elasticsearch.action.search.SearchRequestBuilder)27 IOException (java.io.IOException)25 Map (java.util.Map)23 ElasticsearchAssertions.assertSearchResponse (org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse)20 HashMap (java.util.HashMap)19 IndexRequestBuilder (org.elasticsearch.action.index.IndexRequestBuilder)17 SearchRequest (org.elasticsearch.action.search.SearchRequest)16 Terms (org.elasticsearch.search.aggregations.bucket.terms.Terms)16 TopHits (org.elasticsearch.search.aggregations.metrics.tophits.TopHits)15 SearchSourceBuilder (org.elasticsearch.search.builder.SearchSourceBuilder)14 TotalHits (org.apache.lucene.search.TotalHits)12 Test (org.junit.Test)12 ScoreDoc (org.apache.lucene.search.ScoreDoc)11 Text (org.elasticsearch.common.text.Text)11 InnerHitBuilder (org.elasticsearch.index.query.InnerHitBuilder)11 QueryBuilder (org.elasticsearch.index.query.QueryBuilder)10