Search in sources :

Example 1 with JanusGraphSchemaType

use of org.janusgraph.core.schema.JanusGraphSchemaType 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 JanusGraphSchemaType

use of org.janusgraph.core.schema.JanusGraphSchemaType in project janusgraph by JanusGraph.

the class JanusGraphTest method testGetTTLFromUnsupportedType.

@Test(expected = IllegalArgumentException.class)
public void testGetTTLFromUnsupportedType() {
    if (!features.hasCellTTL()) {
        throw new IllegalArgumentException();
    }
    JanusGraphSchemaType type = ImplicitKey.ID;
    mgmt.getTTL(type);
}
Also used : JanusGraphSchemaType(org.janusgraph.core.schema.JanusGraphSchemaType) Test(org.junit.Test)

Example 3 with JanusGraphSchemaType

use of org.janusgraph.core.schema.JanusGraphSchemaType in project janusgraph by JanusGraph.

the class JanusGraphTest method testSettingTTLOnUnsupportedType.

@Test(expected = IllegalArgumentException.class)
public void testSettingTTLOnUnsupportedType() {
    if (!features.hasCellTTL()) {
        throw new IllegalArgumentException();
    }
    JanusGraphSchemaType type = ImplicitKey.ID;
    mgmt.setTTL(type, Duration.ZERO);
}
Also used : JanusGraphSchemaType(org.janusgraph.core.schema.JanusGraphSchemaType) Test(org.junit.Test)

Example 4 with JanusGraphSchemaType

use of org.janusgraph.core.schema.JanusGraphSchemaType in project janusgraph by JanusGraph.

the class IndexTypeWrapper method getSchemaTypeConstraint.

@Override
public JanusGraphSchemaType getSchemaTypeConstraint() {
    JanusGraphSchemaType constraint;
    if (!cachedTypeConstraint) {
        Iterable<SchemaSource.Entry> related = base.getRelated(TypeDefinitionCategory.INDEX_SCHEMA_CONSTRAINT, Direction.OUT);
        if (Iterables.isEmpty(related)) {
            constraint = null;
        } else {
            constraint = (JanusGraphSchemaType) Iterables.getOnlyElement(related, null).getSchemaType();
            assert constraint != null;
        }
        schemaTypeConstraint = constraint;
        cachedTypeConstraint = true;
    } else {
        constraint = schemaTypeConstraint;
    }
    return constraint;
}
Also used : JanusGraphSchemaType(org.janusgraph.core.schema.JanusGraphSchemaType)

Aggregations

JanusGraphSchemaType (org.janusgraph.core.schema.JanusGraphSchemaType)4 Test (org.junit.Test)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 Cmp (org.janusgraph.core.attribute.Cmp)1 SchemaStatus (org.janusgraph.core.schema.SchemaStatus)1 IndexSerializer (org.janusgraph.graphdb.database.IndexSerializer)1 ElementCategory (org.janusgraph.graphdb.internal.ElementCategory)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 QueryProfiler (org.janusgraph.graphdb.query.profile.QueryProfiler)1 StandardJanusGraphTx (org.janusgraph.graphdb.transaction.StandardJanusGraphTx)1