Search in sources :

Example 6 with Var

use of ai.grakn.graql.Var in project grakn by graknlabs.

the class MatchModifierTest method testVoteCountOrderedQuery.

@Test
public void testVoteCountOrderedQuery() {
    Var z = var("z");
    Match match = qb.match(z.isa("movie").has("tmdb-vote-count", var("v"))).orderBy("v", desc);
    // Make sure movies are in the correct order
    assertThat(match, variable(z, contains(godfather, hocusPocus, apocalypseNow, theMuppets, chineseCoffee)));
}
Also used : Var(ai.grakn.graql.Var) Match(ai.grakn.graql.Match) Test(org.junit.Test)

Example 7 with Var

use of ai.grakn.graql.Var in project grakn by graknlabs.

the class RelationshipAtom method materialise.

@Override
public Stream<Answer> materialise() {
    RelationshipType relationType = getSchemaConcept().asRelationshipType();
    Multimap<Role, Var> roleVarMap = getRoleVarMap();
    Answer substitution = getParentQuery().getSubstitution();
    Relationship relationship = RelationshipTypeImpl.from(relationType).addRelationshipInferred();
    roleVarMap.asMap().forEach((key, value) -> value.forEach(var -> relationship.addRolePlayer(key, substitution.get(var).asThing())));
    Answer relationSub = getRoleSubstitution().merge(getVarName().isUserDefinedName() ? new QueryAnswer(ImmutableMap.of(getVarName(), relationship)) : new QueryAnswer());
    return Stream.of(substitution.merge(relationSub));
}
Also used : Role(ai.grakn.concept.Role) ArrayListMultimap(com.google.common.collect.ArrayListMultimap) Pair(ai.grakn.graql.internal.reasoner.utils.Pair) Atom(ai.grakn.graql.internal.reasoner.atom.Atom) VarPattern(ai.grakn.graql.VarPattern) RelationshipProperty(ai.grakn.graql.internal.pattern.property.RelationshipProperty) RelationshipTypeImpl(ai.grakn.kb.internal.concept.RelationshipTypeImpl) Graql(ai.grakn.graql.Graql) ReasonerUtils.top(ai.grakn.graql.internal.reasoner.utils.ReasonerUtils.top) Type(ai.grakn.concept.Type) MultiUnifierImpl(ai.grakn.graql.internal.reasoner.MultiUnifierImpl) EntityType(ai.grakn.concept.EntityType) HashMultimap(com.google.common.collect.HashMultimap) Label(ai.grakn.concept.Label) RelationshipType(ai.grakn.concept.RelationshipType) GraknTx(ai.grakn.GraknTx) Map(java.util.Map) ReasonerUtils.supers(ai.grakn.graql.internal.reasoner.utils.ReasonerUtils.supers) RoleConverter(ai.grakn.graql.internal.reasoner.utils.conversion.RoleConverter) ConceptId(ai.grakn.concept.ConceptId) Collectors.toSet(java.util.stream.Collectors.toSet) ImmutableSet(com.google.common.collect.ImmutableSet) ValuePredicate(ai.grakn.graql.internal.reasoner.atom.predicate.ValuePredicate) ImmutableMap(com.google.common.collect.ImmutableMap) Collection(java.util.Collection) Set(java.util.Set) IdPredicate(ai.grakn.graql.internal.reasoner.atom.predicate.IdPredicate) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) Objects(java.util.Objects) Atomic(ai.grakn.graql.admin.Atomic) List(java.util.List) Stream(java.util.stream.Stream) Var(ai.grakn.graql.Var) AutoValue(com.google.auto.value.AutoValue) ReasonerUtils.compatibleRoles(ai.grakn.graql.internal.reasoner.utils.ReasonerUtils.compatibleRoles) UnifierType(ai.grakn.graql.internal.reasoner.UnifierType) Iterables(com.google.common.collect.Iterables) ReasonerQueryImpl(ai.grakn.graql.internal.reasoner.query.ReasonerQueryImpl) Role(ai.grakn.concept.Role) Concept(ai.grakn.concept.Concept) SchemaConcept(ai.grakn.concept.SchemaConcept) ReasonerUtils.compatibleRelationTypesWithRoles(ai.grakn.graql.internal.reasoner.utils.ReasonerUtils.compatibleRelationTypesWithRoles) HashMap(java.util.HashMap) Answer(ai.grakn.graql.admin.Answer) Multimap(com.google.common.collect.Multimap) Rule(ai.grakn.concept.Rule) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ReasonerUtils.multimapIntersection(ai.grakn.graql.internal.reasoner.utils.ReasonerUtils.multimapIntersection) ImmutableList(com.google.common.collect.ImmutableList) CommonUtil(ai.grakn.util.CommonUtil) Predicate(ai.grakn.graql.internal.reasoner.atom.predicate.Predicate) Relationship(ai.grakn.concept.Relationship) QueryAnswer(ai.grakn.graql.internal.query.QueryAnswer) ImmutableMultimap(com.google.common.collect.ImmutableMultimap) TypeConverter(ai.grakn.graql.internal.reasoner.utils.conversion.TypeConverter) Nullable(javax.annotation.Nullable) ErrorMessage(ai.grakn.util.ErrorMessage) GraqlQueryException(ai.grakn.exception.GraqlQueryException) Iterator(java.util.Iterator) Memoized(com.google.auto.value.extension.memoized.Memoized) MultiUnifier(ai.grakn.graql.admin.MultiUnifier) UnifierImpl(ai.grakn.graql.internal.reasoner.UnifierImpl) ReasonerUtils(ai.grakn.graql.internal.reasoner.utils.ReasonerUtils) VarProperty(ai.grakn.graql.admin.VarProperty) ReasonerQuery(ai.grakn.graql.admin.ReasonerQuery) IsaProperty(ai.grakn.graql.internal.pattern.property.IsaProperty) UnifierComparison(ai.grakn.graql.admin.UnifierComparison) RelationPlayer(ai.grakn.graql.admin.RelationPlayer) VarPatternAdmin(ai.grakn.graql.admin.VarPatternAdmin) Schema(ai.grakn.util.Schema) Pattern(ai.grakn.graql.Pattern) Comparator(java.util.Comparator) Unifier(ai.grakn.graql.admin.Unifier) Answer(ai.grakn.graql.admin.Answer) QueryAnswer(ai.grakn.graql.internal.query.QueryAnswer) QueryAnswer(ai.grakn.graql.internal.query.QueryAnswer) Var(ai.grakn.graql.Var) Relationship(ai.grakn.concept.Relationship) RelationshipType(ai.grakn.concept.RelationshipType)

Example 8 with Var

use of ai.grakn.graql.Var in project grakn by graknlabs.

the class ResolutionPlan method isValid.

/**
 * @return true if the plan doesn't lead to any non-ground neq predicate
 */
private boolean isValid() {
    // check for neq groundness
    Set<NeqPredicate> nonGroundPredicates = new HashSet<>();
    Set<Var> mappedVars = new HashSet<>();
    for (Atom atom : plan) {
        mappedVars.addAll(atom.getVarNames());
        atom.getPredicates(NeqPredicate.class).forEach(neq -> {
            // look for non-local non-ground predicates
            if (!mappedVars.containsAll(neq.getVarNames()) && !atom.getVarNames().containsAll(neq.getVarNames())) {
                nonGroundPredicates.add(neq);
            } else {
                // if this is ground for this atom but non-ground for another it is ground
                if (nonGroundPredicates.contains(neq))
                    nonGroundPredicates.remove(neq);
            }
        });
    }
    return nonGroundPredicates.isEmpty();
}
Also used : NeqPredicate(ai.grakn.graql.internal.reasoner.atom.predicate.NeqPredicate) Var(ai.grakn.graql.Var) Atom(ai.grakn.graql.internal.reasoner.atom.Atom) HashSet(java.util.HashSet)

Example 9 with Var

use of ai.grakn.graql.Var in project grakn by graknlabs.

the class QueryOperationExecutor method create.

private static QueryOperationExecutor create(Collection<VarPatternAdmin> patterns, GraknTx graph, ExecutionType executionType) {
    ImmutableSet<VarAndProperty> properties = patterns.stream().flatMap(pattern -> VarAndProperty.fromPattern(pattern, executionType)).collect(toImmutableSet());
    /*
            We build several many-to-many relations, indicated by a `Multimap<X, Y>`. These are used to represent
            the dependencies between properties and variables.

            `propDependencies.containsEntry(prop, var)` indicates that the property `prop` cannot be inserted until
            the concept represented by the variable `var` is created.

            For example, the property `$x isa $y` depends on the existence of the concept represented by `$y`.
         */
    Multimap<VarAndProperty, Var> propDependencies = HashMultimap.create();
    for (VarAndProperty property : properties) {
        for (Var requiredVar : property.executor().requiredVars()) {
            propDependencies.put(property, requiredVar);
        }
    }
    /*
            `varDependencies.containsEntry(var, prop)` indicates that the concept represented by the variable `var`
            cannot be created until the property `prop` is inserted.

            For example, the concept represented by `$x` will not exist before the property `$x isa $y` is inserted.
         */
    Multimap<Var, VarAndProperty> varDependencies = HashMultimap.create();
    for (VarAndProperty property : properties) {
        for (Var producedVar : property.executor().producedVars()) {
            varDependencies.put(producedVar, property);
        }
    }
    /*
            Equivalent vars are variables that must represent the same concept as another var.

                 $X label movie, sub entity;
                 $Y label movie;
                 $z isa $Y;

            In this example, `$z isa $Y` must not be inserted before `$Y` is. However, `$Y` does not have enough
            information to insert on its own. It also needs a super type!

            We know `$Y` must represent the same concept as `$X`, because they both share the same label property.
            Therefore, we can share their dependencies, such that:

                varDependencies.containsEntry($X, prop) <=> varDependencies.containsEntry($Y, prop)

            Therefore:

                varDependencies.containsEntry($X, `$X sub entity`) => varDependencies.containsEntry($Y, `$X sub entity`)

            Now we know that `$Y` depends on `$X sub entity` as well as `$X label movie`, which is enough information to
            insert the type!
         */
    Partition<Var> equivalentVars = Partition.singletons(Collections.emptyList());
    equivalentProperties(properties).asMap().values().forEach(vars -> {
        // These vars must refer to the same concept, so share their dependencies
        Collection<VarAndProperty> producers = vars.stream().flatMap(var -> varDependencies.get(var).stream()).collect(toList());
        Var first = vars.iterator().next();
        vars.forEach(var -> {
            varDependencies.replaceValues(var, producers);
            equivalentVars.merge(first, var);
        });
    });
    /*
            Together, `propDependencies` and `varDependencies` can be composed into a single many-to-many relation:

                dependencies = propDependencies ∘ varDependencies

            By doing so, we map _directly_ between properties, skipping the vars. For example, if we previously had:

                propDependencies.containsEntry(`$x isa $y`, `$y`);         // `$x isa $y` depends on `$y`
                varDependencies.containsEntry(`$y`, `$y label movie`);     // `$y` depends on `$y label movie`

            Then it follows that:

                dependencies.containsEntry(`$x isa $y`, `$y label movie`); // `$x isa $y` depends on `$y label movie`

            The `dependencies` relation contains all the information to decide what order to execute the properties.
         */
    Multimap<VarAndProperty, VarAndProperty> dependencies = composeMultimaps(propDependencies, varDependencies);
    return new QueryOperationExecutor(graph, properties, equivalentVars, ImmutableMultimap.copyOf(dependencies));
}
Also used : PropertyExecutor(ai.grakn.graql.internal.pattern.property.PropertyExecutor) Concept(ai.grakn.concept.Concept) InsertQuery(ai.grakn.graql.InsertQuery) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) Answer(ai.grakn.graql.admin.Answer) Multimap(com.google.common.collect.Multimap) Multimaps(com.google.common.collect.Multimaps) HashMultimap(com.google.common.collect.HashMultimap) Lists(com.google.common.collect.Lists) ImmutableList(com.google.common.collect.ImmutableList) Partition(ai.grakn.graql.internal.util.Partition) GraknTx(ai.grakn.GraknTx) Map(java.util.Map) QueryAnswer(ai.grakn.graql.internal.query.QueryAnswer) ImmutableMultimap(com.google.common.collect.ImmutableMultimap) Nullable(javax.annotation.Nullable) CommonUtil.toImmutableSet(ai.grakn.util.CommonUtil.toImmutableSet) Patterns(ai.grakn.graql.internal.pattern.Patterns) VarPropertyInternal(ai.grakn.graql.internal.pattern.property.VarPropertyInternal) GraqlQueryException(ai.grakn.exception.GraqlQueryException) ImmutableSet(com.google.common.collect.ImmutableSet) Logger(org.slf4j.Logger) ImmutableMap(com.google.common.collect.ImmutableMap) Collection(java.util.Collection) Set(java.util.Set) Maps(com.google.common.collect.Maps) Query(ai.grakn.graql.Query) Sets(com.google.common.collect.Sets) VarProperty(ai.grakn.graql.admin.VarProperty) Collectors.toList(java.util.stream.Collectors.toList) Stream(java.util.stream.Stream) Var(ai.grakn.graql.Var) AutoValue(com.google.auto.value.AutoValue) DefineQuery(ai.grakn.graql.DefineQuery) VarPatternAdmin(ai.grakn.graql.admin.VarPatternAdmin) Optional(java.util.Optional) Queue(java.util.Queue) ArrayDeque(java.util.ArrayDeque) Collections(java.util.Collections) Var(ai.grakn.graql.Var)

Example 10 with Var

use of ai.grakn.graql.Var in project grakn by graknlabs.

the class QueryVisitor method visitPropHas.

@Override
public UnaryOperator<VarPattern> visitPropHas(GraqlParser.PropHasContext ctx) {
    Label type = visitLabel(ctx.label());
    VarPattern relation = Optional.ofNullable(ctx.relation).map(this::getVariable).orElseGet(Graql::var);
    VarPattern resource = Optional.ofNullable(ctx.resource).map(this::getVariable).orElseGet(Graql::var);
    if (ctx.predicate() != null) {
        resource = resource.val(visitPredicate(ctx.predicate()));
    }
    VarPattern finalResource = resource;
    return var -> var.has(type, finalResource, relation);
}
Also used : VarPattern(ai.grakn.graql.VarPattern) Token(org.antlr.v4.runtime.Token) Graql(ai.grakn.graql.Graql) ConnectedComponentQuery(ai.grakn.graql.analytics.ConnectedComponentQuery) UnaryOperator(java.util.function.UnaryOperator) Label(ai.grakn.concept.Label) Map(java.util.Map) ComputeQuery(ai.grakn.graql.ComputeQuery) ConceptId(ai.grakn.concept.ConceptId) Aggregate(ai.grakn.graql.Aggregate) MinQuery(ai.grakn.graql.analytics.MinQuery) Collectors.toSet(java.util.stream.Collectors.toSet) QueryBuilder(ai.grakn.graql.QueryBuilder) MaxQuery(ai.grakn.graql.analytics.MaxQuery) ImmutableSet(com.google.common.collect.ImmutableSet) AggregateQuery(ai.grakn.graql.AggregateQuery) ImmutableMap(com.google.common.collect.ImmutableMap) Graql.eq(ai.grakn.graql.Graql.eq) Collection(java.util.Collection) StringUtil(ai.grakn.util.StringUtil) Set(java.util.Set) ValuePredicate(ai.grakn.graql.ValuePredicate) TerminalNode(org.antlr.v4.runtime.tree.TerminalNode) Match(ai.grakn.graql.Match) List(java.util.List) GraqlParser(ai.grakn.graql.internal.antlr.GraqlParser) Stream(java.util.stream.Stream) LocalDate(java.time.LocalDate) Var(ai.grakn.graql.Var) DefineQuery(ai.grakn.graql.DefineQuery) Optional(java.util.Optional) ParserRuleContext(org.antlr.v4.runtime.ParserRuleContext) DegreeQuery(ai.grakn.graql.analytics.DegreeQuery) DeleteQuery(ai.grakn.graql.DeleteQuery) GraqlBaseVisitor(ai.grakn.graql.internal.antlr.GraqlBaseVisitor) StdQuery(ai.grakn.graql.analytics.StdQuery) InsertQuery(ai.grakn.graql.InsertQuery) LocalDateTime(java.time.LocalDateTime) Function(java.util.function.Function) PathQuery(ai.grakn.graql.analytics.PathQuery) AttributeType(ai.grakn.concept.AttributeType) MeanQuery(ai.grakn.graql.analytics.MeanQuery) CommonUtil(ai.grakn.util.CommonUtil) SumQuery(ai.grakn.graql.analytics.SumQuery) GraqlQueryException(ai.grakn.exception.GraqlQueryException) Graql.label(ai.grakn.graql.Graql.label) GetQuery(ai.grakn.graql.GetQuery) Query(ai.grakn.graql.Query) MedianQuery(ai.grakn.graql.analytics.MedianQuery) Graql.and(ai.grakn.graql.Graql.and) Collectors.toList(java.util.stream.Collectors.toList) Order(ai.grakn.graql.Order) NamedAggregate(ai.grakn.graql.NamedAggregate) DateTimeFormatter(java.time.format.DateTimeFormatter) CountQuery(ai.grakn.graql.analytics.CountQuery) PathsQuery(ai.grakn.graql.analytics.PathsQuery) Pattern(ai.grakn.graql.Pattern) Label(ai.grakn.concept.Label) VarPattern(ai.grakn.graql.VarPattern) Graql(ai.grakn.graql.Graql)

Aggregations

Var (ai.grakn.graql.Var)100 Test (org.junit.Test)29 Answer (ai.grakn.graql.admin.Answer)28 ConceptId (ai.grakn.concept.ConceptId)26 Concept (ai.grakn.concept.Concept)25 Role (ai.grakn.concept.Role)25 VarPatternAdmin (ai.grakn.graql.admin.VarPatternAdmin)24 HashSet (java.util.HashSet)24 Set (java.util.Set)24 VarPattern (ai.grakn.graql.VarPattern)21 IdPredicate (ai.grakn.graql.internal.reasoner.atom.predicate.IdPredicate)21 Sets (com.google.common.collect.Sets)20 Map (java.util.Map)20 Stream (java.util.stream.Stream)20 GraqlQueryException (ai.grakn.exception.GraqlQueryException)19 ImmutableSet (com.google.common.collect.ImmutableSet)19 HashMap (java.util.HashMap)19 QueryAnswer (ai.grakn.graql.internal.query.QueryAnswer)18 List (java.util.List)18 SchemaConcept (ai.grakn.concept.SchemaConcept)17