Search in sources :

Example 1 with ElementCategory

use of org.janusgraph.graphdb.internal.ElementCategory in project janusgraph by JanusGraph.

the class GraphCentricQueryBuilder method constructQueryWithoutProfile.

public GraphCentricQuery constructQueryWithoutProfile(final ElementCategory resultType) {
    Preconditions.checkNotNull(resultType);
    if (limit == 0)
        return GraphCentricQuery.emptyQuery(resultType);
    // Prepare constraints
    And<JanusGraphElement> conditions = QueryUtil.constraints2QNF(tx, constraints);
    if (conditions == null)
        return GraphCentricQuery.emptyQuery(resultType);
    // Prepare orders
    orders.makeImmutable();
    if (orders.isEmpty())
        orders = OrderList.NO_ORDER;
    // Compile all indexes that cover at least one of the query conditions
    final Set<IndexType> indexCandidates = new HashSet<>();
    ConditionUtil.traversal(conditions, condition -> {
        if (condition instanceof PredicateCondition) {
            final RelationType type = ((PredicateCondition<RelationType, JanusGraphElement>) condition).getKey();
            Preconditions.checkArgument(type != null && type.isPropertyKey());
            Iterables.addAll(indexCandidates, Iterables.filter(((InternalRelationType) type).getKeyIndexes(), indexType -> indexType.getElement() == resultType));
        }
        return true;
    });
    /*
        Determine the best join index query to answer this query:
        Iterate over all potential indexes (as compiled above) and compute a score based on how many clauses
        this index covers. The index with the highest score (as long as it covers at least one additional clause)
        is picked and added to the joint query for as long as such exist.
         */
    JointIndexQuery jointQuery = new JointIndexQuery();
    boolean isSorted = orders.isEmpty();
    Set<Condition> coveredClauses = Sets.newHashSet();
    while (true) {
        IndexType bestCandidate = null;
        double candidateScore = 0.0;
        Set<Condition> candidateSubcover = null;
        boolean candidateSupportsSort = false;
        Object candidateSubCondition = null;
        for (IndexType index : indexCandidates) {
            Set<Condition> subcover = Sets.newHashSet();
            Object subCondition;
            boolean supportsSort = orders.isEmpty();
            // Check that this index actually applies in case of a schema constraint
            if (index.hasSchemaTypeConstraint()) {
                JanusGraphSchemaType type = index.getSchemaTypeConstraint();
                Map.Entry<Condition, Collection<Object>> equalCon = getEqualityConditionValues(conditions, ImplicitKey.LABEL);
                if (equalCon == null)
                    continue;
                Collection<Object> labels = equalCon.getValue();
                assert labels.size() >= 1;
                if (labels.size() > 1) {
                    log.warn("The query optimizer currently does not support multiple label constraints in query: {}", this);
                    continue;
                }
                if (!type.name().equals(Iterables.getOnlyElement(labels))) {
                    continue;
                }
                subcover.add(equalCon.getKey());
            }
            if (index.isCompositeIndex()) {
                subCondition = indexCover((CompositeIndexType) index, conditions, subcover);
            } else {
                subCondition = indexCover((MixedIndexType) index, conditions, serializer, subcover);
                if (coveredClauses.isEmpty() && !supportsSort && indexCoversOrder((MixedIndexType) index, orders))
                    supportsSort = true;
            }
            if (subCondition == null)
                continue;
            assert !subcover.isEmpty();
            double score = 0.0;
            boolean coversAdditionalClause = false;
            for (Condition c : subcover) {
                double s = (c instanceof PredicateCondition && ((PredicateCondition) c).getPredicate() == Cmp.EQUAL) ? EQUAL_CONDITION_SCORE : OTHER_CONDITION_SCORE;
                if (coveredClauses.contains(c))
                    s = s * ALREADY_MATCHED_ADJUSTOR;
                else
                    coversAdditionalClause = true;
                score += s;
                if (index.isCompositeIndex())
                    score += ((CompositeIndexType) index).getCardinality() == Cardinality.SINGLE ? CARDINALITY_SINGE_SCORE : CARDINALITY_OTHER_SCORE;
            }
            if (supportsSort)
                score += ORDER_MATCH;
            if (coversAdditionalClause && score > candidateScore) {
                candidateScore = score;
                bestCandidate = index;
                candidateSubcover = subcover;
                candidateSubCondition = subCondition;
                candidateSupportsSort = supportsSort;
            }
        }
        if (bestCandidate != null) {
            if (coveredClauses.isEmpty())
                isSorted = candidateSupportsSort;
            coveredClauses.addAll(candidateSubcover);
            if (bestCandidate.isCompositeIndex()) {
                jointQuery.add((CompositeIndexType) bestCandidate, serializer.getQuery((CompositeIndexType) bestCandidate, (List<Object[]>) candidateSubCondition));
            } else {
                jointQuery.add((MixedIndexType) bestCandidate, serializer.getQuery((MixedIndexType) bestCandidate, (Condition) candidateSubCondition, orders));
            }
        } else {
            break;
        }
    /* TODO: smarter optimization:
            - use in-memory histograms to estimate selectivity of PredicateConditions and filter out low-selectivity ones
                    if they would result in an individual index call (better to filter afterwards in memory)
            - move OR's up and extend GraphCentricQuery to allow multiple JointIndexQuery for proper or'ing of queries
            */
    }
    BackendQueryHolder<JointIndexQuery> query;
    if (!coveredClauses.isEmpty()) {
        int indexLimit = limit == Query.NO_LIMIT ? HARD_MAX_LIMIT : limit;
        if (tx.getGraph().getConfiguration().adjustQueryLimit()) {
            indexLimit = limit == Query.NO_LIMIT ? DEFAULT_NO_LIMIT : Math.min(MAX_BASE_LIMIT, limit);
        }
        indexLimit = Math.min(HARD_MAX_LIMIT, QueryUtil.adjustLimitForTxModifications(tx, coveredClauses.size(), indexLimit));
        jointQuery.setLimit(indexLimit);
        query = new BackendQueryHolder<>(jointQuery, coveredClauses.size() == conditions.numChildren(), isSorted);
    } else {
        query = new BackendQueryHolder<>(new JointIndexQuery(), false, isSorted);
    }
    return new GraphCentricQuery(resultType, conditions, orders, query, limit);
}
Also used : JanusGraphSchemaType(org.janusgraph.core.schema.JanusGraphSchemaType) org.janusgraph.graphdb.query(org.janusgraph.graphdb.query) Iterables(com.google.common.collect.Iterables) java.util(java.util) QueryProfiler(org.janusgraph.graphdb.query.profile.QueryProfiler) Logger(org.slf4j.Logger) StandardJanusGraphTx(org.janusgraph.graphdb.transaction.StandardJanusGraphTx) org.janusgraph.graphdb.query.condition(org.janusgraph.graphdb.query.condition) LoggerFactory(org.slf4j.LoggerFactory) org.janusgraph.core(org.janusgraph.core) org.janusgraph.graphdb.types(org.janusgraph.graphdb.types) IndexSerializer(org.janusgraph.graphdb.database.IndexSerializer) Sets(com.google.common.collect.Sets) ElementCategory(org.janusgraph.graphdb.internal.ElementCategory) Order(org.janusgraph.graphdb.internal.Order) OrderList(org.janusgraph.graphdb.internal.OrderList) ImmutableList(com.google.common.collect.ImmutableList) Cmp(org.janusgraph.core.attribute.Cmp) ImplicitKey(org.janusgraph.graphdb.types.system.ImplicitKey) SchemaStatus(org.janusgraph.core.schema.SchemaStatus) Preconditions(com.google.common.base.Preconditions) StreamSupport(java.util.stream.StreamSupport) InternalRelationType(org.janusgraph.graphdb.internal.InternalRelationType) InternalRelationType(org.janusgraph.graphdb.internal.InternalRelationType) OrderList(org.janusgraph.graphdb.internal.OrderList) ImmutableList(com.google.common.collect.ImmutableList) InternalRelationType(org.janusgraph.graphdb.internal.InternalRelationType) JanusGraphSchemaType(org.janusgraph.core.schema.JanusGraphSchemaType)

Example 2 with ElementCategory

use of org.janusgraph.graphdb.internal.ElementCategory in project janusgraph by JanusGraph.

the class IndexSerializerTest method mockIndexAppliesTo.

private JanusGraphElement mockIndexAppliesTo(MixedIndexType mit, boolean indexable) {
    String key = "foo";
    String value = "bar";
    JanusGraphElement indexableElement = mockIndexableElement(key, value, indexable);
    ElementCategory ec = ElementCategory.VERTEX;
    doReturn(ec).when(mit).getElement();
    doReturn(false).when(mit).hasSchemaTypeConstraint();
    PropertyKey pk = mock(PropertyKey.class);
    doReturn(1L).when(pk).longId();
    doReturn(key).when(pk).name();
    ParameterIndexField pif = mock(ParameterIndexField.class);
    Parameter[] parameter = { new Parameter(key, value) };
    doReturn(parameter).when(pif).getParameters();
    doReturn(SchemaStatus.REGISTERED).when(pif).getStatus();
    doReturn(pk).when(pif).getFieldKey();
    ParameterIndexField[] ifField = { pif };
    doReturn(ifField).when(mit).getFieldKeys();
    return indexableElement;
}
Also used : JanusGraphElement(org.janusgraph.core.JanusGraphElement) ElementCategory(org.janusgraph.graphdb.internal.ElementCategory) Parameter(org.janusgraph.core.schema.Parameter) ParameterIndexField(org.janusgraph.graphdb.types.ParameterIndexField) PropertyKey(org.janusgraph.core.PropertyKey)

Aggregations

ElementCategory (org.janusgraph.graphdb.internal.ElementCategory)2 Preconditions (com.google.common.base.Preconditions)1 ImmutableList (com.google.common.collect.ImmutableList)1 Iterables (com.google.common.collect.Iterables)1 Sets (com.google.common.collect.Sets)1 java.util (java.util)1 StreamSupport (java.util.stream.StreamSupport)1 org.janusgraph.core (org.janusgraph.core)1 JanusGraphElement (org.janusgraph.core.JanusGraphElement)1 PropertyKey (org.janusgraph.core.PropertyKey)1 Cmp (org.janusgraph.core.attribute.Cmp)1 JanusGraphSchemaType (org.janusgraph.core.schema.JanusGraphSchemaType)1 Parameter (org.janusgraph.core.schema.Parameter)1 SchemaStatus (org.janusgraph.core.schema.SchemaStatus)1 IndexSerializer (org.janusgraph.graphdb.database.IndexSerializer)1 InternalRelationType (org.janusgraph.graphdb.internal.InternalRelationType)1 Order (org.janusgraph.graphdb.internal.Order)1 OrderList (org.janusgraph.graphdb.internal.OrderList)1 org.janusgraph.graphdb.query (org.janusgraph.graphdb.query)1 org.janusgraph.graphdb.query.condition (org.janusgraph.graphdb.query.condition)1