Example usage for org.apache.lucene.search.join ScoreMode Max

List of usage examples for org.apache.lucene.search.join ScoreMode Max

Introduction

In this page you can find the example usage for org.apache.lucene.search.join ScoreMode Max.

Prototype

ScoreMode Max

To view the source code for org.apache.lucene.search.join ScoreMode Max.

Click Source Link

Document

Parent hit's score is the max of all child scores.

Usage

From source file:net.stargraph.core.impl.elastic.ElasticEntitySearcher.java

License:Open Source License

@Override
public Scores classSearch(ModifiableSearchParams searchParams, ModifiableRankParams rankParams) {

    searchParams.model(BuiltInModel.FACT);

    if (rankParams instanceof ModifiableIndraParams) {
        configureDistributionalParams(searchParams.getKbId(), (ModifiableIndraParams) rankParams);
    }//from  ww  w  . ja v  a  2  s  .  c o m

    QueryBuilder queryBuilder = boolQuery().must(nestedQuery("p", termQuery("p.id", "is-a"), ScoreMode.Max))
            .should(nestedQuery("o", matchQuery("o.value", searchParams.getSearchTerm()), ScoreMode.Max))
            .minimumShouldMatch("1");

    Searcher searcher = core.getSearcher(searchParams.getKbId());
    Scores scores = searcher.search(new ElasticQueryHolder(queryBuilder, searchParams));

    List<Score> classes2Score = scores.stream()
            .map(s -> new Score(((Fact) s.getEntry()).getObject(), s.getValue())).collect(Collectors.toList());

    return Rankers.apply(new Scores(classes2Score), rankParams, searchParams.getSearchTerm());
}

From source file:net.stargraph.core.impl.elastic.ElasticEntitySearcher.java

License:Open Source License

@Override
public Scores propertySearch(ModifiableSearchParams searchParams, ModifiableRankParams rankParams) {

    searchParams.model(BuiltInModel.PROPERTY);

    if (rankParams instanceof ModifiableIndraParams) {
        configureDistributionalParams(searchParams.getKbId(), (ModifiableIndraParams) rankParams);
    }//  ww  w. j  a v a  2s.c  om

    QueryBuilder queryBuilder = boolQuery()
            .should(nestedQuery("hyponyms", matchQuery("hyponyms.word", searchParams.getSearchTerm()),
                    ScoreMode.Max))
            .should(nestedQuery("hypernyms", matchQuery("hypernyms.word", searchParams.getSearchTerm()),
                    ScoreMode.Max))
            .should(nestedQuery("synonyms", matchQuery("synonyms.word", searchParams.getSearchTerm()),
                    ScoreMode.Max))
            .minimumNumberShouldMatch(1);

    Searcher searcher = core.getSearcher(searchParams.getKbId());
    Scores scores = searcher.search(new ElasticQueryHolder(queryBuilder, searchParams));

    return Rankers.apply(scores, rankParams, searchParams.getSearchTerm());
}

From source file:net.stargraph.core.impl.elastic.ElasticEntitySearcher.java

License:Open Source License

@Override
public Scores pivotedSearch(InstanceEntity pivot, ModifiableSearchParams searchParams,
        ModifiableRankParams rankParams) {

    searchParams.model(BuiltInModel.FACT);

    if (rankParams instanceof ModifiableIndraParams) {
        configureDistributionalParams(searchParams.getKbId(), (ModifiableIndraParams) rankParams);
    }//  w w  w. j a v a 2s.c  om

    QueryBuilder queryBuilder = boolQuery()
            .should(nestedQuery("s", termQuery("s.id", pivot.getId()), ScoreMode.Max))
            .should(nestedQuery("o", termQuery("o.id", pivot.getId()), ScoreMode.Max))
            .minimumNumberShouldMatch(1);

    Searcher searcher = core.getSearcher(searchParams.getKbId());
    Scores scores = searcher.search(new ElasticQueryHolder(queryBuilder, searchParams));

    // We have to remap the facts to properties, the real target of the ranker call.
    // Thus we're discarding the score values from the underlying search engine. Shall we?
    Scores propScores = new Scores(scores.stream().map(s -> ((Fact) s.getEntry()).getPredicate()).distinct()
            .map(p -> new Score(p, 0)).collect(Collectors.toList()));

    return Rankers.apply(propScores, rankParams, searchParams.getSearchTerm());
}

From source file:net.stargraph.core.impl.elastic.ElasticSearchQueryGenerator.java

License:Open Source License

@Override
public SearchQueryHolder findClassFacts(ModifiableSearchParams searchParams) {

    QueryBuilder queryBuilder = boolQuery().must(nestedQuery("p", termQuery("p.id", "is-a"), ScoreMode.Max))
            .should(nestedQuery("o", matchQuery("o.value", searchParams.getSearchTerm()), ScoreMode.Max))
            .minimumShouldMatch("1");

    return new ElasticQueryHolder(queryBuilder, searchParams);
}

From source file:net.stargraph.core.impl.elastic.ElasticSearchQueryGenerator.java

License:Open Source License

@Override
public SearchQueryHolder findPropertyInstances(ModifiableSearchParams searchParams) {
    QueryBuilder queryBuilder = boolQuery()
            .should(nestedQuery("hyponyms", matchQuery("hyponyms.word", searchParams.getSearchTerm()),
                    ScoreMode.Max))
            .should(nestedQuery("hypernyms", matchQuery("hypernyms.word", searchParams.getSearchTerm()),
                    ScoreMode.Max))//from   ww  w.  j a v  a2s  .c o m
            .should(nestedQuery("synonyms", matchQuery("synonyms.word", searchParams.getSearchTerm()),
                    ScoreMode.Max))
            .minimumNumberShouldMatch(1);

    return new ElasticQueryHolder(queryBuilder, searchParams);
}

From source file:net.stargraph.core.impl.elastic.ElasticSearchQueryGenerator.java

License:Open Source License

@Override
public SearchQueryHolder findPivotFacts(InstanceEntity pivot, ModifiableSearchParams searchParams) {
    QueryBuilder queryBuilder = boolQuery()
            .should(nestedQuery("s", termQuery("s.id", pivot.getId()), ScoreMode.Max))
            .should(nestedQuery("o", termQuery("o.id", pivot.getId()), ScoreMode.Max))
            .minimumNumberShouldMatch(1);

    return new ElasticQueryHolder(queryBuilder, searchParams);
}

From source file:org.codelibs.elasticsearch.index.query.HasChildQueryBuilder.java

License:Apache License

public static ScoreMode parseScoreMode(String scoreModeString) {
    if ("none".equals(scoreModeString)) {
        return ScoreMode.None;
    } else if ("min".equals(scoreModeString)) {
        return ScoreMode.Min;
    } else if ("max".equals(scoreModeString)) {
        return ScoreMode.Max;
    } else if ("avg".equals(scoreModeString)) {
        return ScoreMode.Avg;
    } else if ("sum".equals(scoreModeString)) {
        return ScoreMode.Total;
    }/*from   w  ww .  ja v  a2 s .  c om*/
    throw new IllegalArgumentException("No score mode for child query [" + scoreModeString + "] found");
}

From source file:org.elasticsearch.benchmark.search.child.ChildSearchBenchmark.java

License:Apache License

public static void main(String[] args) throws Exception {
    boolean bwcMode = false;
    int numParents = (int) SizeValue.parseSizeValue("2m").singles();
    ;/*from  w w w.j  av a2s .  c o m*/

    if (args.length % 2 != 0) {
        throw new IllegalArgumentException("Uneven number of arguments");
    }
    for (int i = 0; i < args.length; i += 2) {
        String value = args[i + 1];
        if ("--bwc_mode".equals(args[i])) {
            bwcMode = Boolean.valueOf(value);
        } else if ("--num_parents".equals(args[i])) {
            numParents = Integer.valueOf(value);
        }
    }

    Settings.Builder settings = settingsBuilder().put("index.refresh_interval", "-1")
            .put(SETTING_NUMBER_OF_SHARDS, 1).put(SETTING_NUMBER_OF_REPLICAS, 0);

    // enable bwc parent child mode:
    if (bwcMode) {
        settings.put("tests.mock.version", Version.V_1_6_0);
    }

    String clusterName = ChildSearchBenchmark.class.getSimpleName();
    Node node1 = nodeBuilder().clusterName(clusterName)
            .settings(settingsBuilder().put(settings.build()).put("name", "node1")).node();
    Client client = node1.client();

    int CHILD_COUNT = 15;
    int QUERY_VALUE_RATIO = 3;
    int QUERY_WARMUP = 10;
    int QUERY_COUNT = 20;
    String indexName = "test";

    ParentChildIndexGenerator parentChildIndexGenerator = new ParentChildIndexGenerator(client, numParents,
            CHILD_COUNT, QUERY_VALUE_RATIO);
    client.admin().cluster().prepareHealth(indexName).setWaitForGreenStatus().setTimeout("10s").execute()
            .actionGet();
    try {
        client.admin().indices().create(createIndexRequest(indexName)).actionGet();
        client.admin().indices().preparePutMapping(indexName).setType("child")
                .setSource(XContentFactory.jsonBuilder().startObject().startObject("child")
                        .startObject("_parent").field("type", "parent").endObject().endObject().endObject())
                .execute().actionGet();
        Thread.sleep(5000);
        long startTime = System.currentTimeMillis();
        parentChildIndexGenerator.index();
        System.out.println(
                "--> Indexing took " + ((System.currentTimeMillis() - startTime) / 1000) + " seconds.");
    } catch (IndexAlreadyExistsException e) {
        System.out.println("--> Index already exists, ignoring indexing phase, waiting for green");
        ClusterHealthResponse clusterHealthResponse = client.admin().cluster().prepareHealth(indexName)
                .setWaitForGreenStatus().setTimeout("10m").execute().actionGet();
        if (clusterHealthResponse.isTimedOut()) {
            System.err.println("--> Timed out waiting for cluster health");
        }
    }
    client.admin().indices().prepareRefresh().execute().actionGet();
    System.out.println("--> Number of docs in index: " + client.prepareSearch(indexName).setSize(0)
            .setQuery(matchAllQuery()).execute().actionGet().getHits().totalHits());

    System.out.println("--> Running just child query");
    // run just the child query, warm up first
    for (int j = 0; j < QUERY_WARMUP; j++) {
        client.prepareSearch(indexName).setQuery(termQuery("child.tag", "tag1")).execute().actionGet();
    }

    long totalQueryTime = 0;
    for (int j = 0; j < QUERY_COUNT; j++) {
        SearchResponse searchResponse = client.prepareSearch(indexName).setQuery(termQuery("child.tag", "tag1"))
                .execute().actionGet();
        totalQueryTime += searchResponse.getTookInMillis();
    }
    System.out.println("--> Just Child Query Avg: " + (totalQueryTime / QUERY_COUNT) + "ms");

    NodesStatsResponse statsResponse = client.admin().cluster().prepareNodesStats().setJvm(true).execute()
            .actionGet();
    System.out.println(
            "--> Committed heap size: " + statsResponse.getNodes()[0].getJvm().getMem().getHeapCommitted());
    System.out.println("--> Used heap size: " + statsResponse.getNodes()[0].getJvm().getMem().getHeapUsed());

    // run parent child constant query
    for (int j = 0; j < QUERY_WARMUP; j++) {
        SearchResponse searchResponse = client.prepareSearch(indexName)
                .setQuery(boolQuery().must(matchAllQuery()).filter(
                        hasChildQuery("child", termQuery("field2", parentChildIndexGenerator.getQueryValue()))))
                .execute().actionGet();
        if (searchResponse.getFailedShards() > 0) {
            System.err.println("Search Failures " + Arrays.toString(searchResponse.getShardFailures()));
        }
    }

    totalQueryTime = 0;
    for (int j = 0; j < QUERY_COUNT; j++) {
        SearchResponse searchResponse = client.prepareSearch(indexName)
                .setQuery(boolQuery().must(matchAllQuery()).filter(
                        hasChildQuery("child", termQuery("field2", parentChildIndexGenerator.getQueryValue()))))
                .execute().actionGet();
        if (searchResponse.getFailedShards() > 0) {
            System.err.println("Search Failures " + Arrays.toString(searchResponse.getShardFailures()));
        }
        if (j % 10 == 0) {
            System.out.println("--> hits [" + j + "], got [" + searchResponse.getHits().totalHits() + "]");
        }
        totalQueryTime += searchResponse.getTookInMillis();
    }
    System.out.println("--> has_child filter Query Avg: " + (totalQueryTime / QUERY_COUNT) + "ms");

    System.out.println("--> Running has_child filter with match_all child query");
    totalQueryTime = 0;
    for (int j = 1; j <= QUERY_COUNT; j++) {
        SearchResponse searchResponse = client.prepareSearch(indexName)
                .setQuery(boolQuery().must(matchAllQuery()).filter(hasChildQuery("child", matchAllQuery())))
                .execute().actionGet();
        if (searchResponse.getFailedShards() > 0) {
            System.err.println("Search Failures " + Arrays.toString(searchResponse.getShardFailures()));
        }
        if (j % 10 == 0) {
            System.out.println("--> hits [" + j + "], got [" + searchResponse.getHits().totalHits() + "]");
        }
        totalQueryTime += searchResponse.getTookInMillis();
    }
    System.out.println("--> has_child filter with match_all child query, Query Avg: "
            + (totalQueryTime / QUERY_COUNT) + "ms");

    System.out.println("--> Running children agg");
    totalQueryTime = 0;
    for (int j = 1; j <= QUERY_COUNT; j++) {
        SearchResponse searchResponse = client.prepareSearch(indexName)
                .setQuery(matchQuery("field1", parentChildIndexGenerator.getQueryValue()))
                .addAggregation(AggregationBuilders.children("to-child").childType("child")).execute()
                .actionGet();
        totalQueryTime += searchResponse.getTookInMillis();
        if (searchResponse.getFailedShards() > 0) {
            System.err.println("Search Failures " + Arrays.toString(searchResponse.getShardFailures()));
        }
        Children children = searchResponse.getAggregations().get("to-child");
        if (j % 10 == 0) {
            System.out.println("--> children doc count [" + j + "], got [" + children.getDocCount() + "]");
        }
    }
    System.out.println("--> children agg, Query Avg: " + (totalQueryTime / QUERY_COUNT) + "ms");

    System.out.println("--> Running children agg with match_all");
    totalQueryTime = 0;
    for (int j = 1; j <= QUERY_COUNT; j++) {
        SearchResponse searchResponse = client.prepareSearch(indexName)
                .addAggregation(AggregationBuilders.children("to-child").childType("child")).execute()
                .actionGet();
        totalQueryTime += searchResponse.getTookInMillis();
        if (searchResponse.getFailedShards() > 0) {
            System.err.println("Search Failures " + Arrays.toString(searchResponse.getShardFailures()));
        }
        Children children = searchResponse.getAggregations().get("to-child");
        if (j % 10 == 0) {
            System.out.println("--> children doc count [" + j + "], got [" + children.getDocCount() + "]");
        }
    }
    System.out.println("--> children agg, Query Avg: " + (totalQueryTime / QUERY_COUNT) + "ms");

    // run parent child constant query
    for (int j = 0; j < QUERY_WARMUP; j++) {
        SearchResponse searchResponse = client.prepareSearch(indexName)
                .setQuery(boolQuery().must(matchAllQuery())
                        .filter(hasParentQuery("parent",
                                termQuery("field1", parentChildIndexGenerator.getQueryValue()))))
                .execute().actionGet();
        if (searchResponse.getFailedShards() > 0) {
            System.err.println("Search Failures " + Arrays.toString(searchResponse.getShardFailures()));
        }
    }

    totalQueryTime = 0;
    for (int j = 1; j <= QUERY_COUNT; j++) {
        SearchResponse searchResponse = client.prepareSearch(indexName)
                .setQuery(boolQuery().must(matchAllQuery())
                        .filter(hasParentQuery("parent",
                                termQuery("field1", parentChildIndexGenerator.getQueryValue()))))
                .execute().actionGet();
        if (searchResponse.getFailedShards() > 0) {
            System.err.println("Search Failures " + Arrays.toString(searchResponse.getShardFailures()));
        }
        if (j % 10 == 0) {
            System.out.println("--> hits [" + j + "], got [" + searchResponse.getHits().totalHits() + "]");
        }
        totalQueryTime += searchResponse.getTookInMillis();
    }
    System.out.println("--> has_parent filter Query Avg: " + (totalQueryTime / QUERY_COUNT) + "ms");

    System.out.println("--> Running has_parent filter with match_all parent query ");
    totalQueryTime = 0;
    for (int j = 1; j <= QUERY_COUNT; j++) {
        SearchResponse searchResponse = client.prepareSearch(indexName)
                .setQuery(boolQuery().must(matchAllQuery()).filter(hasParentQuery("parent", matchAllQuery())))
                .execute().actionGet();
        if (searchResponse.getFailedShards() > 0) {
            System.err.println("Search Failures " + Arrays.toString(searchResponse.getShardFailures()));
        }
        if (j % 10 == 0) {
            System.out.println("--> hits [" + j + "], got [" + searchResponse.getHits().totalHits() + "]");
        }
        totalQueryTime += searchResponse.getTookInMillis();
    }
    System.out.println("--> has_parent filter with match_all parent query, Query Avg: "
            + (totalQueryTime / QUERY_COUNT) + "ms");

    statsResponse = client.admin().cluster().prepareNodesStats().setJvm(true).setIndices(true).execute()
            .actionGet();

    System.out.println(
            "--> Field data size: " + statsResponse.getNodes()[0].getIndices().getFieldData().getMemorySize());
    System.out.println("--> Used heap size: " + statsResponse.getNodes()[0].getJvm().getMem().getHeapUsed());

    System.out.println("--> Running has_child query with score type");
    // run parent child score query
    for (int j = 0; j < QUERY_WARMUP; j++) {
        client.prepareSearch(indexName)
                .setQuery(hasChildQuery("child", termQuery("field2", parentChildIndexGenerator.getQueryValue()))
                        .scoreMode(ScoreMode.Max))
                .execute().actionGet();
    }

    totalQueryTime = 0;
    for (int j = 0; j < QUERY_COUNT; j++) {
        SearchResponse searchResponse = client.prepareSearch(indexName)
                .setQuery(hasChildQuery("child", termQuery("field2", parentChildIndexGenerator.getQueryValue()))
                        .scoreMode(ScoreMode.Max))
                .execute().actionGet();
        if (j % 10 == 0) {
            System.out.println("--> hits [" + j + "], got [" + searchResponse.getHits().totalHits() + "]");
        }
        totalQueryTime += searchResponse.getTookInMillis();
    }
    System.out.println("--> has_child Query Avg: " + (totalQueryTime / QUERY_COUNT) + "ms");

    totalQueryTime = 0;
    for (int j = 0; j < QUERY_COUNT; j++) {
        SearchResponse searchResponse = client.prepareSearch(indexName)
                .setQuery(hasChildQuery("child", matchAllQuery()).scoreMode(ScoreMode.Max)).execute()
                .actionGet();
        if (j % 10 == 0) {
            System.out.println("--> hits [" + j + "], got [" + searchResponse.getHits().totalHits() + "]");
        }
        totalQueryTime += searchResponse.getTookInMillis();
    }
    System.out
            .println("--> has_child query with match_all Query Avg: " + (totalQueryTime / QUERY_COUNT) + "ms");

    System.out.println("--> Running has_parent query with score type");
    // run parent child score query
    for (int j = 0; j < QUERY_WARMUP; j++) {
        client.prepareSearch(indexName)
                .setQuery(
                        hasParentQuery("parent", termQuery("field1", parentChildIndexGenerator.getQueryValue()))
                                .score(true))
                .execute().actionGet();
    }

    totalQueryTime = 0;
    for (int j = 1; j < QUERY_COUNT; j++) {
        SearchResponse searchResponse = client.prepareSearch(indexName)
                .setQuery(
                        hasParentQuery("parent", termQuery("field1", parentChildIndexGenerator.getQueryValue()))
                                .score(true))
                .execute().actionGet();
        if (j % 10 == 0) {
            System.out.println("--> hits [" + j + "], got [" + searchResponse.getHits().totalHits() + "]");
        }
        totalQueryTime += searchResponse.getTookInMillis();
    }
    System.out.println("--> has_parent Query Avg: " + (totalQueryTime / QUERY_COUNT) + "ms");

    totalQueryTime = 0;
    for (int j = 1; j < QUERY_COUNT; j++) {
        SearchResponse searchResponse = client.prepareSearch(indexName)
                .setQuery(hasParentQuery("parent", matchAllQuery()).score(true)).execute().actionGet();
        if (j % 10 == 0) {
            System.out.println("--> hits [" + j + "], got [" + searchResponse.getHits().totalHits() + "]");
        }
        totalQueryTime += searchResponse.getTookInMillis();
    }
    System.out
            .println("--> has_parent query with match_all Query Avg: " + (totalQueryTime / QUERY_COUNT) + "ms");

    System.gc();
    statsResponse = client.admin().cluster().prepareNodesStats().setJvm(true).setIndices(true).execute()
            .actionGet();

    System.out.println(
            "--> Field data size: " + statsResponse.getNodes()[0].getIndices().getFieldData().getMemorySize());
    System.out.println("--> Used heap size: " + statsResponse.getNodes()[0].getJvm().getMem().getHeapUsed());

    client.close();
    node1.close();
}

From source file:org.elasticsearch.benchmark.search.child.ChildSearchShortCircuitBenchmark.java

License:Apache License

public static void main(String[] args) throws Exception {
    Settings settings = settingsBuilder().put("index.refresh_interval", "-1").put(SETTING_NUMBER_OF_SHARDS, 1)
            .put(SETTING_NUMBER_OF_REPLICAS, 0).build();

    String clusterName = ChildSearchShortCircuitBenchmark.class.getSimpleName();
    Node node1 = nodeBuilder().clusterName(clusterName)
            .settings(settingsBuilder().put(settings).put("name", "node1")).node();
    Client client = node1.client();/*  ww w . j  a v a2 s  .  c o  m*/

    long PARENT_COUNT = SizeValue.parseSizeValue("10M").singles();
    int BATCH = 100;
    int QUERY_WARMUP = 5;
    int QUERY_COUNT = 25;
    String indexName = "test";

    client.admin().cluster().prepareHealth(indexName).setWaitForGreenStatus().setTimeout("10s").execute()
            .actionGet();
    try {
        client.admin().indices().create(createIndexRequest(indexName)).actionGet();
        client.admin().indices().preparePutMapping(indexName).setType("child")
                .setSource(XContentFactory.jsonBuilder().startObject().startObject("child")
                        .startObject("_parent").field("type", "parent").endObject().endObject().endObject())
                .execute().actionGet();
        Thread.sleep(5000);

        StopWatch stopWatch = new StopWatch().start();

        System.out.println("--> Indexing [" + PARENT_COUNT + "] parent document and some child documents");
        long ITERS = PARENT_COUNT / BATCH;
        int i = 1;
        int counter = 0;
        for (; i <= ITERS; i++) {
            BulkRequestBuilder request = client.prepareBulk();
            for (int j = 0; j < BATCH; j++) {
                counter++;
                request.add(Requests.indexRequest(indexName).type("parent").id(Integer.toString(counter))
                        .source(parentSource(counter)));

            }
            BulkResponse response = request.execute().actionGet();
            if (response.hasFailures()) {
                System.err.println("--> failures...");
            }
            if (((i * BATCH) % 10000) == 0) {
                System.out.println(
                        "--> Indexed " + (i * BATCH) + "parent docs; took " + stopWatch.stop().lastTaskTime());
                stopWatch.start();
            }
        }

        int id = 0;
        for (i = 1; i <= PARENT_COUNT; i *= 2) {
            int parentId = 1;
            for (int j = 0; j < i; j++) {
                client.prepareIndex(indexName, "child", Integer.toString(id++))
                        .setParent(Integer.toString(parentId++)).setSource(childSource(i)).execute()
                        .actionGet();
            }
        }

        System.out.println("--> Indexing took " + stopWatch.totalTime());
    } catch (Exception e) {
        System.out.println("--> Index already exists, ignoring indexing phase, waiting for green");
        ClusterHealthResponse clusterHealthResponse = client.admin().cluster().prepareHealth(indexName)
                .setWaitForGreenStatus().setTimeout("10m").execute().actionGet();
        if (clusterHealthResponse.isTimedOut()) {
            System.err.println("--> Timed out waiting for cluster health");
        }
    }
    client.admin().indices().prepareRefresh().execute().actionGet();
    System.out.println("--> Number of docs in index: " + client.prepareSearch(indexName).setSize(0)
            .setQuery(matchAllQuery()).execute().actionGet().getHits().totalHits());

    System.out.println("--> Running just child query");
    // run just the child query, warm up first
    for (int i = 1; i <= 10000; i *= 2) {
        SearchResponse searchResponse = client.prepareSearch(indexName).setQuery(matchQuery("child.field2", i))
                .execute().actionGet();
        System.out.println("--> Warmup took[" + i + "]: " + searchResponse.getTook());
        if (searchResponse.getHits().totalHits() != i) {
            System.err.println("--> mismatch on hits");
        }
    }

    NodesStatsResponse statsResponse = client.admin().cluster().prepareNodesStats().setJvm(true).execute()
            .actionGet();
    System.out.println(
            "--> Committed heap size: " + statsResponse.getNodes()[0].getJvm().getMem().getHeapCommitted());
    System.out.println("--> Used heap size: " + statsResponse.getNodes()[0].getJvm().getMem().getHeapUsed());

    // run parent child constant query
    for (int j = 1; j < QUERY_WARMUP; j *= 2) {
        SearchResponse searchResponse = client.prepareSearch(indexName)
                .setQuery(hasChildQuery("child", matchQuery("field2", j))).execute().actionGet();
        if (searchResponse.getFailedShards() > 0) {
            System.err.println("Search Failures " + Arrays.toString(searchResponse.getShardFailures()));
        }
        if (searchResponse.getHits().totalHits() != j) {
            System.err.println("--> mismatch on hits [" + j + "], got [" + searchResponse.getHits().totalHits()
                    + "], expected [" + PARENT_COUNT + "]");
        }
    }

    long totalQueryTime = 0;
    for (int i = 1; i < PARENT_COUNT; i *= 2) {
        for (int j = 0; j < QUERY_COUNT; j++) {
            SearchResponse searchResponse = client.prepareSearch(indexName).setQuery(
                    boolQuery().must(matchAllQuery()).filter(hasChildQuery("child", matchQuery("field2", i))))
                    .execute().actionGet();
            if (searchResponse.getHits().totalHits() != i) {
                System.err.println("--> mismatch on hits");
            }
            totalQueryTime += searchResponse.getTookInMillis();
        }
        System.out.println("--> has_child filter " + i + " Avg: " + (totalQueryTime / QUERY_COUNT) + "ms");
    }

    statsResponse = client.admin().cluster().prepareNodesStats().setJvm(true).setIndices(true).execute()
            .actionGet();

    System.out.println(
            "--> Field data size: " + statsResponse.getNodes()[0].getIndices().getFieldData().getMemorySize());
    System.out.println("--> Used heap size: " + statsResponse.getNodes()[0].getJvm().getMem().getHeapUsed());

    totalQueryTime = 0;
    for (int i = 1; i < PARENT_COUNT; i *= 2) {
        for (int j = 0; j < QUERY_COUNT; j++) {
            SearchResponse searchResponse = client.prepareSearch(indexName)
                    .setQuery(hasChildQuery("child", matchQuery("field2", i)).scoreMode(ScoreMode.Max))
                    .execute().actionGet();
            if (searchResponse.getHits().totalHits() != i) {
                System.err.println("--> mismatch on hits");
            }
            totalQueryTime += searchResponse.getTookInMillis();
        }
        System.out.println("--> has_child query " + i + " Avg: " + (totalQueryTime / QUERY_COUNT) + "ms");
    }

    System.gc();
    statsResponse = client.admin().cluster().prepareNodesStats().setJvm(true).setIndices(true).execute()
            .actionGet();

    System.out.println(
            "--> Field data size: " + statsResponse.getNodes()[0].getIndices().getFieldData().getMemorySize());
    System.out.println("--> Used heap size: " + statsResponse.getNodes()[0].getJvm().getMem().getHeapUsed());

    client.close();
    node1.close();
}

From source file:org.elasticsearch.index.query.HasChildQueryBuilderTests.java

License:Apache License

public void testMaxFromString() {
    assertThat("fromString(max) != MAX", ScoreMode.Max, equalTo(HasChildQueryBuilder.parseScoreMode("max")));
    assertThat("max", equalTo(HasChildQueryBuilder.scoreModeAsString(ScoreMode.Max)));
}