Search in sources :

Example 26 with Keyspace

use of ai.grakn.Keyspace in project grakn by graknlabs.

the class BenchmarkIT method loadRuleChainData.

private void loadRuleChainData(int N) {
    final GraknClient graknClient = GraknClient.of(engine.uri());
    String entityLabel = "genericEntity";
    String attributeLabel = "index";
    String baseRelationLabel = "relation1";
    String genericRelationLabel = "relation";
    String fromRoleLabel = "fromRole";
    String toRoleLabel = "toRole";
    // load ontology
    try (GraknTx tx = session.open(GraknTxType.WRITE)) {
        Role fromRole = tx.putRole(fromRoleLabel);
        Role toRole = tx.putRole(toRoleLabel);
        AttributeType<String> index = tx.putAttributeType(attributeLabel, AttributeType.DataType.STRING);
        tx.putEntityType(entityLabel).plays(fromRole).plays(toRole).attribute(index);
        // define N relation types
        for (int i = 1; i <= N; i++) {
            tx.putRelationshipType(genericRelationLabel + i).relates(fromRole).relates(toRole);
        }
        // define N rules
        for (int i = 2; i <= N; i++) {
            Var fromVar = Graql.var().asUserDefined();
            Var intermedVar = Graql.var().asUserDefined();
            Var toVar = Graql.var().asUserDefined();
            VarPattern rulePattern = Graql.label("rule" + i).when(Graql.and(Graql.var().rel(Graql.label(fromRole.getLabel()), fromVar).rel(Graql.label(toRole.getLabel()), intermedVar).isa(baseRelationLabel), Graql.var().rel(Graql.label(fromRole.getLabel()), intermedVar).rel(Graql.label(toRole.getLabel()), toVar).isa(genericRelationLabel + (i - 1)))).then(Graql.and(Graql.var().rel(Graql.label(fromRole.getLabel()), fromVar).rel(Graql.label(toRole.getLabel()), toVar).isa(genericRelationLabel + i)));
            tx.graql().define(rulePattern).execute();
        }
        tx.commit();
    }
    // insert N + 1 entities
    loadEntities(entityLabel, N + 1, graknClient, keyspace);
    // load initial relation instances
    try (BatchExecutorClient loader = BatchExecutorClient.newBuilder().taskClient(graknClient).build()) {
        try (GraknTx tx = session.open(GraknTxType.READ)) {
            Var entityVar = var().asUserDefined();
            ConceptId[] instances = tx.graql().match(entityVar.isa(entityLabel)).get().execute().stream().map(ans -> ans.get(entityVar).getId()).toArray(ConceptId[]::new);
            RelationshipType baseRelation = tx.getRelationshipType(baseRelationLabel);
            Role fromRole = tx.getRole(fromRoleLabel);
            Role toRole = tx.getRole(toRoleLabel);
            loader.add(Graql.insert(Graql.var().asUserDefined().has(attributeLabel, "first").id(instances[0]).admin().varPatterns()), keyspace).subscribe();
            for (int i = 1; i < instances.length; i++) {
                Var fromRolePlayer = Graql.var();
                Var toRolePlayer = Graql.var();
                Pattern relationInsert = Graql.var().rel(Graql.label(fromRole.getLabel()), fromRolePlayer).rel(Graql.label(toRole.getLabel()), toRolePlayer).isa(Graql.label(baseRelation.getLabel())).and(fromRolePlayer.asUserDefined().id(instances[i - 1])).and(toRolePlayer.asUserDefined().id(instances[i]));
                loader.add(Graql.insert(relationInsert.admin().varPatterns()), keyspace).subscribe();
                Pattern resourceInsert = Graql.var().asUserDefined().has(attributeLabel, String.valueOf(i)).id(instances[i]);
                loader.add(Graql.insert(resourceInsert.admin().varPatterns()), keyspace).subscribe();
            }
        }
    }
}
Also used : Iterables(com.google.common.collect.Iterables) VarPattern(ai.grakn.graql.VarPattern) Keyspace(ai.grakn.Keyspace) Role(ai.grakn.concept.Role) Assume.assumeFalse(org.junit.Assume.assumeFalse) InsertQuery(ai.grakn.graql.InsertQuery) LoggerFactory(org.slf4j.LoggerFactory) Graql(ai.grakn.graql.Graql) Random(java.util.Random) Answer(ai.grakn.graql.admin.Answer) Multimap(com.google.common.collect.Multimap) HashMultimap(com.google.common.collect.HashMultimap) Charset(java.nio.charset.Charset) AttributeType(ai.grakn.concept.AttributeType) RelationshipType(ai.grakn.concept.RelationshipType) Files(com.google.common.io.Files) GraknTx(ai.grakn.GraknTx) GraknClient(ai.grakn.client.GraknClient) ConceptId(ai.grakn.concept.ConceptId) ClassRule(org.junit.ClassRule) Grakn(ai.grakn.Grakn) GraknSystemProperty(ai.grakn.GraknSystemProperty) EngineContext(ai.grakn.test.rule.EngineContext) Before(org.junit.Before) GraknTxType(ai.grakn.GraknTxType) Graql.var(ai.grakn.graql.Graql.var) BatchExecutorClient(ai.grakn.client.BatchExecutorClient) Logger(org.slf4j.Logger) GraknSession(ai.grakn.GraknSession) Test(org.junit.Test) GetQuery(ai.grakn.graql.GetQuery) File(java.io.File) GraknTestUtil.usingTinker(ai.grakn.util.GraknTestUtil.usingTinker) List(java.util.List) SampleKBLoader.randomKeyspace(ai.grakn.util.SampleKBLoader.randomKeyspace) Var(ai.grakn.graql.Var) Pattern(ai.grakn.graql.Pattern) Assert.assertEquals(org.junit.Assert.assertEquals) VarPattern(ai.grakn.graql.VarPattern) Pattern(ai.grakn.graql.Pattern) Var(ai.grakn.graql.Var) RelationshipType(ai.grakn.concept.RelationshipType) ConceptId(ai.grakn.concept.ConceptId) Role(ai.grakn.concept.Role) GraknTx(ai.grakn.GraknTx) GraknClient(ai.grakn.client.GraknClient) VarPattern(ai.grakn.graql.VarPattern) BatchExecutorClient(ai.grakn.client.BatchExecutorClient)

Example 27 with Keyspace

use of ai.grakn.Keyspace in project grakn by graknlabs.

the class GraknTxTinkerFactoryTest method whenGettingGraphFromFactoryWithAlreadyOpenGraph_Throw.

@Test
public void whenGettingGraphFromFactoryWithAlreadyOpenGraph_Throw() {
    Keyspace mytest = Keyspace.of("mytest");
    when(session.keyspace()).thenReturn(mytest);
    TxFactoryTinker factory = new TxFactoryTinker(session);
    factory.open(GraknTxType.WRITE);
    expectedException.expect(GraknTxOperationException.class);
    expectedException.expectMessage(TRANSACTION_ALREADY_OPEN.getMessage("mytest"));
    factory.open(GraknTxType.WRITE);
}
Also used : Keyspace(ai.grakn.Keyspace) Test(org.junit.Test)

Example 28 with Keyspace

use of ai.grakn.Keyspace in project grakn by graknlabs.

the class ConceptController method getSchemaByLabel.

private String getSchemaByLabel(Request request, Response response) throws JsonProcessingException {
    Requests.validateRequest(request, APPLICATION_ALL, APPLICATION_JSON);
    Keyspace keyspace = Keyspace.of(mandatoryPathParameter(request, KEYSPACE_PARAM));
    Label label = Label.of(mandatoryPathParameter(request, LABEL_PARAMETER));
    return getConcept(response, keyspace, (tx) -> tx.getSchemaConcept(label));
}
Also used : Keyspace(ai.grakn.Keyspace) Label(ai.grakn.concept.Label)

Example 29 with Keyspace

use of ai.grakn.Keyspace in project grakn by graknlabs.

the class GrpcOpenRequestExecutorImpl method execute.

@Override
public EmbeddedGraknTx<?> execute(Open request) {
    Keyspace keyspace = GrpcUtil.getKeyspace(request);
    GraknTxType txType = GrpcUtil.getTxType(request);
    return txFactory.tx(keyspace, txType);
}
Also used : GraknTxType(ai.grakn.GraknTxType) Keyspace(ai.grakn.Keyspace)

Example 30 with Keyspace

use of ai.grakn.Keyspace in project grakn by graknlabs.

the class GraqlController method executeGraql.

@POST
@Path("/kb/{keyspace}/graql")
private String executeGraql(Request request, Response response) throws RetryException, ExecutionException {
    Keyspace keyspace = Keyspace.of(mandatoryPathParameter(request, KEYSPACE_PARAM));
    String queryString = mandatoryBody(request);
    // Run the query with reasoning on or off
    Optional<Boolean> infer = queryParameter(request, EXECUTE_WITH_INFERENCE).map(Boolean::parseBoolean);
    // Allow multiple queries to be executed
    boolean multiQuery = parseBoolean(queryParameter(request, ALLOW_MULTIPLE_QUERIES).orElse("false"));
    // Define all anonymous variables in the query
    Optional<Boolean> defineAllVars = queryParameter(request, DEFINE_ALL_VARS).map(Boolean::parseBoolean);
    // Used to check if serialisation of results is needed. When loading we skip this for the sake of speed
    boolean skipSerialisation = parseBoolean(queryParameter(request, LOADING_DATA).orElse("false"));
    // Check the transaction type to use
    GraknTxType txType = queryParameter(request, TX_TYPE).map(String::toUpperCase).map(GraknTxType::valueOf).orElse(GraknTxType.WRITE);
    // This is used to determine the response format
    // TODO: Maybe we should really try to stick with one representation? This would require dashboard console interpreting the json representation
    final String acceptType;
    if (APPLICATION_TEXT.equals(Requests.getAcceptType(request))) {
        acceptType = APPLICATION_TEXT;
    } else {
        acceptType = APPLICATION_JSON;
    }
    response.type(APPLICATION_JSON);
    // Execute the query and get the results
    LOG.debug("Executing graql query: {}", StringUtils.abbreviate(queryString, 100));
    LOG.trace("Full query: {}", queryString);
    return executeFunctionWithRetrying(() -> {
        try (EmbeddedGraknTx<?> tx = factory.tx(keyspace, txType);
            Timer.Context context = executeGraql.time()) {
            QueryBuilder builder = tx.graql();
            infer.ifPresent(builder::infer);
            QueryParser parser = builder.parser();
            defineAllVars.ifPresent(parser::defineAllVars);
            response.status(SC_OK);
            return executeQuery(tx, queryString, acceptType, multiQuery, skipSerialisation, parser);
        } finally {
            LOG.debug("Executed graql query");
        }
    });
}
Also used : GraknTxType(ai.grakn.GraknTxType) QueryBuilder(ai.grakn.graql.QueryBuilder) QueryParser(ai.grakn.graql.QueryParser) Timer(com.codahale.metrics.Timer) Keyspace(ai.grakn.Keyspace) Boolean.parseBoolean(java.lang.Boolean.parseBoolean) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST)

Aggregations

Keyspace (ai.grakn.Keyspace)30 Test (org.junit.Test)14 GraknTx (ai.grakn.GraknTx)9 GraknTxType (ai.grakn.GraknTxType)7 ConceptId (ai.grakn.concept.ConceptId)7 List (java.util.List)6 BatchExecutorClient (ai.grakn.client.BatchExecutorClient)5 Timer (com.codahale.metrics.Timer)5 LoggerFactory (org.slf4j.LoggerFactory)5 GraknSession (ai.grakn.GraknSession)4 Role (ai.grakn.concept.Role)4 InsertQuery (ai.grakn.graql.InsertQuery)4 SimpleURI (ai.grakn.util.SimpleURI)4 Before (org.junit.Before)4 Logger (org.slf4j.Logger)4 GraknClient (ai.grakn.client.GraknClient)3 AttributeType (ai.grakn.concept.AttributeType)3 EntityType (ai.grakn.concept.EntityType)3 RelationshipType (ai.grakn.concept.RelationshipType)3 Graql (ai.grakn.graql.Graql)3