Pular para o conteúdo principal

GSQL x Query using Context Meta-information (Edges Properties)

Testes no ambiente de Cloud do TigerGraph -> https://tgcloud.io/app/solutions

Usando o python notebook no Google Collab -> https://colab.research.google.com/drive/1vCfaTCO5lCxyMswqC8sukty0_OwrBqjP?usp=sharing

Passos

Define and Publish the Schema
Contexto temporal definido pelo atributo date_of_start

# DEFINE / CREATE ALL EDGES AND VERTICES

  USE GLOBAL
  DROP ALL
  CREATE VERTEX Person (PRIMARY_ID id STRING, name STRING, email STRING, username STRING, created_at DATETIME) WITH primary_id_as_attribute="true"
  CREATE VERTEX Country (PRIMARY_ID id STRING, name STRING, language STRING, continent STRING, population INT ) WITH primary_id_as_attribute="true"
  CREATE DIRECTED EDGE WORKING_IN (From Person, To Country, date_of_start DATETIME) WITH REVERSE_EDGE="reverse_working"
  CREATE DIRECTED EDGE LIVING_IN (From Person, To Country, date_of_start DATETIME) WITH REVERSE_EDGE="reverse_living"
  CREATE DIRECTED EDGE FRIENDS_WITH (From Person, To Person, date_of_start DATETIME) WITH REVERSE_EDGE="reverse_friends"

Create the Graph

DROP GRAPH MyGraph
CREATE GRAPH MyGraph(Person, Country, WORKING_IN, LIVING_IN, FRIENDS_WITH, reverse_working, reverse_living, reverse_friends )

Loading Data
Countries

  USE GRAPH MyGraph
  DROP QUERY addCountry
  CREATE QUERY addCountry() FOR GRAPH MyGraph {
    INSERT INTO Country VALUES ("DEU", "Germany", "German", "Europe", 83000000 );
    INSERT INTO Country VALUES ("FRA", "France", "French", "Europe", 67000000 );
    INSERT INTO Country VALUES ("GBR", "United Kingdom", "English", "Europe", 66000000 );
  }
  INTERPRET QUERY addCountry()

Person

  USE GRAPH MyGraph
  DROP QUERY addPerson
  CREATE QUERY addPerson() FOR GRAPH MyGraph {
    INSERT INTO Person VALUES ("John", "John",_,_,_ );
    INSERT INTO Person VALUES ("Harry", "Harry",_,_,_ );
    INSERT INTO Person VALUES ("Anna", "Anna", _,_,_ );
  }
  INTERPRET QUERY addPerson()

Relationships WORKING_IN, LIVING_IN, FRIENDS_WITH

  USE GRAPH MyGraph
  DROP QUERY addRelationships
  CREATE QUERY addRelationships() FOR GRAPH MyGraph {  

    INSERT INTO LIVING_IN VALUES("John", "DEU", to_datetime("2014-01-01"));
    INSERT INTO LIVING_IN VALUES("Harry", "GBR", to_datetime("2013-01-01"));
    INSERT INTO LIVING_IN VALUES("Anna", "DEU", to_datetime("2014-01-01"));
    INSERT INTO LIVING_IN VALUES("Anna", "GBR", to_datetime("2016-01-01"));
    INSERT INTO WORKING_IN VALUES("John", "FRA", to_datetime("2014-01-01"));
    INSERT INTO WORKING_IN VALUES("Harry", "GBR", to_datetime("2014-01-01"));

    INSERT INTO FRIENDS_WITH VALUES("John", "Harry", to_datetime("2011-01-01"));
    INSERT INTO FRIENDS_WITH VALUES("Anna", "John", to_datetime("2012-01-01"));
    INSERT INTO FRIENDS_WITH VALUES("Anna", "Harry", to_datetime("2014-01-01"));

  }
  INTERPRET QUERY addRelationships()


Queries
Queries using start_date

Using SYNTAX V2 for multi-hop
BUT
(SEM-5200): line 46, col 4 Disconnected patterns not yet supported: alias(es) f1 disconnected from rest of pattern

https://dev.tigergraph.com/forum/t/create-query-returns-null/1833

  USE GRAPH MyGraph
  CREATE QUERY start_date_qualifier() FOR GRAPH MyGraph  SYNTAX v2 {
   
    SetAccum<EDGE> @@edges;
    SetAccum<VERTEX> @@source;
    SetAccum<VERTEX> @@target;
 
    PRINT "first query!";
 
    R1 = SELECT p   
    FROM Person:p -((LIVING_IN> | WORKING_IN>):r) -Country:c
    WHERE c.name == "United Kingdom" AND r.date_of_start == to_datetime("2014-01-01")
    ACCUM @@edges += r;
 
    PRINT @@edges;
    reset_collection_accum(@@edges);

    PRINT "second query!";
 
    R2 = SELECT p
    FROM Person:p -(FRIENDS_WITH>:r) -Person:f
    WHERE r.date_of_start > to_datetime("2010-01-01")
    ACCUM @@edges += r, @@source += p, @@target += f;
 
    PRINT @@edges, @@source, @@target;
    reset_collection_accum(@@edges);
    reset_collection_accum(@@source);
    reset_collection_accum(@@target);

    PRINT "third query!";
 
    R3 = SELECT p
    FROM Person:p -(FRIENDS_WITH>:r1) -Person:f1- (FRIENDS_WITH>:r2) -Person:f2
    WHERE r2.date_of_start > r1.date_of_start
    ACCUM @@edges += r2, @@source += p, @@target += f2;
    
    PRINT @@edges, @@source, @@target;
    reset_collection_accum(@@edges);
    reset_collection_accum(@@source);
    reset_collection_accum(@@target);
 
    PRINT "fourth query Failed!";
 
#    R4 = SELECT f1
#    FROM Person:f1- (FRIENDS_WITH>:r1) -Person:f3 , Person:f2- (FRIENDS_WITH>:r2) -Person:f4
#    WHERE r2.date_of_start == r1.date_of_start
#    ACCUM @@edges += r2, @@edges += r1, @@source += f1, @@source += f2, @@target += f3, @@target += f4;
    
    PRINT @@edges, @@source, @@target;
    reset_collection_accum(@@edges);
    reset_collection_accum(@@source);
    reset_collection_accum(@@target);
 
    PRINT "fifth query Failed!";
 
#    R5 = SELECT f1
#    FROM Person:f1- (LIVING_IN>:r1) -Country:c1 , Person:f2- (LIVING_IN>:r2) -Country:c2
#    WHERE r2.date_of_start == r1.date_of_start
#    ACCUM @@edges += r2, @@edges += r1, @@source += f1, @@source += f2, @@target += c1, @@target += c2;
    
    PRINT @@edges, @@source, @@target;
    reset_collection_accum(@@edges);
    reset_collection_accum(@@source);
    reset_collection_accum(@@target);
 
  PRINT "start_date_qual works!";
  }

  INSTALL QUERY start_date_qualifier

conn.runInstalledQuery("start_date_qualifier")

  CREATE QUERY start_date_qualifier_tab() FOR GRAPH MyGraph  SYNTAX v2 {
   
    PRINT "first query!";
 
    SELECT p, r, c into R1   
    FROM Person:p -((LIVING_IN> | WORKING_IN>):r) -Country:c
    WHERE c.name == "United Kingdom" AND r.date_of_start == to_datetime("2014-01-01");
 
    PRINT R1;

    PRINT "second query!";
 
    SELECT p, r, f into R2
    FROM Person:p -(FRIENDS_WITH>:r) -Person:f
    WHERE r.date_of_start > to_datetime("2010-01-01");
 
    PRINT R2;

    PRINT "third query!";
 
    SELECT p, r1, f1, r2, f2 into R3
    FROM Person:p -(FRIENDS_WITH>:r1) -Person:f1- (FRIENDS_WITH>:r2) -Person:f2
    WHERE r2.date_of_start > r1.date_of_start;
    
    PRINT R3;

    PRINT "fourth query Failed!";
 
#    SELECT f1, r1, f3, f2, r2, f4 into R4
#    FROM Person:f1- (FRIENDS_WITH>:r1) -Person:f3 , Person:f2- (FRIENDS_WITH>:r2) -Person:f4
#    WHERE r2.date_of_start == r1.date_of_start;

#   PRINT R4;
 
    PRINT "fifth query Failed!";
 
#    SELECT f1, r1, c1,f2,r2, c2 into R5
#    FROM Person:f1- (LIVING_IN>:r1) -Country:c1 , Person:f2- (LIVING_IN>:r2) -Country:c2
#    WHERE r2.date_of_start == r1.date_of_start;

#    PRINT R5;
 
  PRINT "start_date_qual_tab works!";
  }

  INSTALL QUERY start_date_qualifier_tab

conn.runInstalledQuery("start_date_qualifier_tab")

GSQL Path (10, 37) Error: Kleene star pattern can't have an alias.

  USE GRAPH MyGraph
  CREATE QUERY start_date_qualifier_path(/* Parameters here */) FOR GRAPH MyGraph  SYNTAX v2 {
   
    SetAccum<EDGE> @@edges;
    SetAccum<VERTEX> @@source;
    SetAccum<VERTEX> @@target;
 
    PRINT "path query!";
 
    R2 = SELECT p
    FROM Person:p -(FRIENDS_WITH*1..2:r) -Person:f
    WHERE r.date_of_start > to_datetime("2010-01-01")
    ACCUM @@edges += r, @@source += p, @@target += f;
 
    PRINT @@edges, @@source, @@target;
    reset_collection_accum(@@edges);
    reset_collection_accum(@@source);
    reset_collection_accum(@@target);

  PRINT "start_date_qualifier_path works!";
}

(SEM-2001): line 12, col 37
Kleene star pattern can't have an alias.

Failed to create queries: [start_date_qualifier_path].

Documentação

A query can be run in one of three ways:

    Define and run an unnamed query immediately:

        INTERPRET QUERY: execute the query’s statements

        Alternately, there is also a built-in REST++ endpoint to interpret a query string:
        POST /gsqlserver/interpreted_query
        See the RESTPP API User Guide for details.

    Define a named query and then run it.

        CREATE QUERY: define the functionality of the query

        INTERPRET QUERY: execute the query with input values

    Define a named query, compile it to optimize performance, and then run it.

        CREATE QUERY: define the functionality of the query

        INSTALL QUERY: compile the query

        RUN QUERY: execute the query with input values

Starting with TigerGraph 2.6, there are now two versions of the GSQL Query Language. Both are available in the product. The original version is called GSQL Syntax V1. GSQL Syntax V2 was introduced to provide more flexible and powerful Pattern matching. A query indicates which grammar to use in the SYNTAX clause of the CREATE QUERY header. V1 is the default.

As new features are being added to GSQL, some are available only in V2. In the future, we plan to transition so that Syntax V2 will be the default.

The key differences between the two grammars:

Multi-hop Pattern Matching is only in Syntax V2 (since TigerGraph 2.6)

  • In V2, each SELECT statement can traverse a multi-hop path.

    • The traversal direction is under the control of the query writer, with arrowheads on each edge set to show the direction.

    • There is no arrowhead outside the parentheses:

      Start:s -( (ForwardEdge> | <BackwardEdge):e )- Target:t

    • Users can write paths that explicitly show multiple hops, and they can use a Kleene star (*) to indicate repetition. Start:s -(Edge1>:e1)- Middle:m -(<Edge2:e2)- Target:t or Start:s -(Edge*1..3)- Target:t

      SQL-like Tabular SELECT is only in Syntax V2 (since TigerGraph 3.1)

  • V1 is default when ommited

     

Comentários

Postagens mais visitadas deste blog

Aprendizado de Máquina Relacional

 Extraído de -> https://www.lncc.br/~ziviani/papers/Texto-MC1-SBBD2019.pdf   Aprendizado de máquina relacional (AMR) destina-se à criação de modelos estatísticos para dados relacionais (seria o mesmo que dados conectados) , isto é, dados cuja a informação relacional é tão ou mais impor tante que a informação individual (atributos) de cada elemento.    Essa classe de aprendizado tem sido utilizada em diversas aplicações, por exemplo, na extração de informação de dados não estruturados [Zhang et al. 2016] e na modelagem de linguagem natural [Vu et al. 2018].   A adoção de técnicas de aprendizado de máquina relacional em tarefas de comple mentação de grafo de conhecimento se baseia na premissa de existência de regularidades semânticas presentes no mesmo . Modelos grafos probabilísticos  Baseada em regras / heurísticas que não podem garantir 100% de precisão no resultado da inferência mas os resultados podem ser explicados. Modelos de características de ...

Defesa de Doutorado de Grettel Monteagudo Garcia

A última atividade presencial que fiz na PUC-Rio foi assistir a defesa de tese da Grettel Monteagudo Garcia , em 13/03/2020 (uma sexta-feira 13 !!!!). O título da tese é “ A Keyword-based Query Processing Method for Datasets with Schemas ” e me interessou por causa do projeto do NIMA. A proposta parte do cenário onde usuários possam consultar dados, armazenados em bancos de dados relacionais e TripleStores, de maneira semelhante ao Google, ou seja, digitando palavras-chave, e deixando para o sistema recuperar os dados que melhor correspondem ao conjunto de palavras-chave.  Na tese estão descritos um algoritmo e um framework projetados para processar consultas baseadas em palavras-chave para bases de dados com esquema, especificamente bancos relacionais e bases de dados em RDF. A primeira etapa do algoritmo é a conversão do conjunto de palavras chaves em uma consulta abstrata explorando um esquema abstrato . Nesta etapa o principal desafio é achar onde a informação está (os matches...

Metodologia Científica II - continuação

No primeiro post  foram detalhados os 6 primeiros vídeos do canal do Youtube do professor Eduardo Ogasawara do CEFET/RJ   Mais 3 vídeos foram disponibilizados e estão comentados a seguir: Gráficos, Figuras e Tabelas (33 minutos) - como apresentar os resultados das avaliações experimentais. Gráficos: associar análises dos resultados a cada gráfico apresentado, problemas comuns na montagem de gráficos (não usar todo eixo X ou Y, não usar área útil com uma escala adequada a ver o comportamento dos números, não marcar os pontos de observação da série, inconsistência no uso de cores ), escala logarítmica x linear, eixo X para a variável independente e Y para a dependente (resposta), escrever boas legendas para os gráficos, observar se diferenças entre variáveis apresentadas em gráficos separados podem atrapalhar a interpretação dos resultados. Diagramas devem ser pensados de acordo com o propósito, trata-se de uma abstração e cada elemento deve ser explicado no texto, rótulos...