04 neo4j Flashcards

1
Q

:clear

A

equivalente a cls

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

match (anyX) return anyX

match (anyX) return anyX limit 666

A

retorna tudo da database

retorna no máximo 666 nodos, todas relações entre os 666

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

(node) [relation]
1) match (x1)–(x2) return x1, x2 limit 1
2) match (x1)-[y]-(x2) return x1, y, x2 limit 1

3) match (x1)-[y]-(x2)
return x1, y, x2
limit 1

A

returna um unico nodo x1 com conexao com nodo x2

retorna com mais detalhes

3 = 2

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

match (x1)-[y]->(x2)
return x1, y, x2
limit 1

A

Observar seta

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

match (ator:Person)-[relação:ACTED_IN]->(filme:Movie)
return ator, relação, filme
limit 5

A

retorna 5 relações em que uma Person Acted_In a Movie

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

match (ator:Person)-[relação:ACTED_IN | DIRECTED]->(filme:Movie)
return ator, relação, filme
limit 10

A

retorna 10 relações em que uma Person Acted_In OR Directed a Movie

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

match (filme:Movie)
return filme.title
limit 1

A

Retorna somente a propertie title de um Movie

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

match (filme:Movie)
match (diretor:Person)-[:DIRECTED]->(filme)
match (diretor)-[:ACTED_IN]->(filme)
return filme.title, diretor.name

A

retorna o title do movie e o name da Person que dirirgiu e atuou no filme em questão

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q
match (filme:Movie)
optional match (diretor:Person)-[:DIRECTED]->(filme)
A

retorna todos os filmes da database, naqueles em que o diretor não é também ator, o campo diretor name fica “null”, caso tenha dirigido e atuado aparece o nome dele.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

match (pa:Person)-[:HAS_CONTACT]->(pb:Person)-[:HAS_CONTACT]->(pc:Person)
where pa <> pc
return pa.name, pb.name, pc.name
limit 1

A

retorna os nomes das pessoas pa, pb, pc, sendo pa diferente de pc, em que pa tem contato de pb e pb tem contato de pc

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q
match (p1:Person)-[:HAS_CONTACT]->(p2:Person)
optional match (p2)-[:DIRECTED]->(filme:Movie)
return p1.name, p2.name, filme.title

limite de linhas do neo4j é 1000

A

Retorna as Persons p1 que tem contato com as Persons p2, se essa pessoa dirigiu algum filme, aparece o nome de todos os filmes, caso não tenha dirigido, aparece null

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

match (x {name: ‘Tom Hanks’, born: 1956})
return x

match (x:Person)
where x.name = ‘Tom Hanks’ and x.born = 1956
return x

Sinônimos, Where é melhor

A

Retorna o nodo em que o nome é Tom Hanks e o Ano de Nascimento é 1956

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

neo4j é case sensitive

A

sim

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

match (x:Person)
where x.born <> 1956
return x

A

Retorna as pessoas que não foram nascidas em 1956

> =, >, <=,

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

match (x:Person)
where x.name >= ‘T’
return x

A

Retorna pessoas cujos nomes começam com T ou letra após no alfabeto

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

match (x:Person)
where x.born = 1956 or x.born = 1957 or x.born = 1958
return x

match (x:Person)
where x.born in [1956, 1957, 1958]
return x

A

retorna pessoas que nasceram em 1956, 1957 ou 1958

Sinônimos

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

match (x:Person)
where x.born >= 1950 and x.born < 1960
return x

A

retorna pessoas que nasceram entre 1950 e 1959 (incluindo os dois anos)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q
match (x:Person)
where not (x.born >= 1950 and x.born < 1960)
return count(x)
A

retorna quantas pessoas nasceram 1949 ou antes OU 1960 ou depois

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

match (pessoa:Person)–>(filme:Movie)
where filme.title = ‘Unforgiven’ and not (pessoa)-[:DIRECTED]->(filme)
return pessoa, filme

A

retorna as pessoas que têm alguma relação com o filme Unforgiven exceto ser diretor

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

AND
OR
IN
NOT

A

Booleans

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

match (pessoa:Person)–>(filme:Movie)
where filme.title = ‘Unforgiven’ and not (pessoa)-[:DIRECTED]->(filme)
return pessoa, filme

A

retorna as pessoas que têm alguma relação com o filme Unforgiven exceto ser diretor

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

match (filme:Movie)
where filme.title =~ ‘The.*’
return filme.title

match (filme:Movie)
where filme.title =~ ‘.The.
return filme.title

match (filme:Movie)
where filme.title =~ ‘The .*’
return filme.title

match (filme:Movie)
where filme.title =~ ‘.+The .*’
return filme.title

A

retorna todos os filmes que começam com The

retorna bla bla Their além do The no início do título e no meio

retorna se The tem espaço depois (não retorna Their por exemplo)

.+ significa que nao pode ser a primeira palavra, tem que ser no meio

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

match (valueX:typeX)
where valueX.KeyX =~ ‘(?i).stringX.
return valueX.KeyX

A

(?i) faz virar case insensitive

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

match (ator:Person)-[papel:ACTED_IN]->(filme:Movie)
where filme.title = ‘Top Gun’
return ator.name as Ator, papel.earnings as Ganhos
order by papel.earnings desc
skip 3
limit 2

pode escrever descending no lugar de desc

A

retorna o nome dos atores de Top Gun e quanto cada um ganhou
tabela em ordem descendente de valores
pula os 3 que mais ganharam
retorna do 4 ao 8o (5)
Resultado será uma tabela com 1a coluna Ator e 2a coluna Ganhos

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
match (tom:Person{name: "Tom Hanks"}) match (filme:Movie) match (tom)-[:HAS_CONTACT]->(ator:Person) match (ator)-[papel:ACTED_IN]->(filme) where ator.born >= 1960 and papel.earnings > 10000000 return ator.name as ContactName, ator.born as Born, papel.earnings as Earnings order by papel.earnings desc
Retorna todos os atores que o Tom Hanks tem contato e que foram nascidos em 1960 ou depois e que já gamharam mais de 10 milhões por um único filme Contatos organizados em ordem descendente de ganhos, renomeadas as colunas para ContactName, Born e Earnings
26
match (tom:Person{name: "Tom Hanks"}) match (filme:Movie) match (tom)-[:HAS_CONTACT]->(ator:Person) match (ator)-[papel:ACTED_IN]->(filme) where ator.born >= 1960 and papel.earnings > 10000000 return ator.name as ContactName, ator.born as Born, papel.earnings as Earnings order by papel.earnings desc
Retorna todos os atores que o Tom Hanks tem contato e que foram nascidos em 1960 ou depois e que já gamharam mais de 10 milhões por um único filme Contatos organizados em ordem descendente de ganhos, renomeadas as colunas para ContactName, Born e Earnings
27
match (tom:Person{name: "Tom Hanks"}) match (filme:Movie) match (tom)-[:HAS_CONTACT]->(ator:Person) match (ator)-[papel:ACTED_IN]->(filme) where ator.born >= 1960 and papel.earnings > 10000000 return DISTINCT ator.name as ContactName match (tom:Person{name: "Tom Hanks"}) match (filme:Movie) match (tom)-[:HAS_CONTACT]->(ator:Person) match (ator)-[papel:ACTED_IN]->(filme) where ator.born >= 1960 and papel.earnings > 10000000 return count (DISTINCT ator.name)
Retorna todos os atores que o Tom Hanks tem contato e que foram nascidos em 1960 ou depois e que já gamharam mais de 10 milhões por um único filme, uma única vez por causa do DISTINCT no segundo conta quantos são
28
``` COUNT AVG SUM MIN MAX ```
Aggregations Functions
29
``` match (tom:Person{name: "Tom Hanks"})-[papel:ACTED_IN]->(filme:Movie) return sum (papel.earnings) as TotalEarnings ```
Retorna TotalEarnings do Tom Hanks, a soma de todos os ganhos em todos os filmes em que atuou AVG seria average (média) MAX MIN
30
toString (xxx) toUpper (xxx), toLower
transforma xxx em "xxx" transforma xxx em XXX, o contrário
31
return replace ("oh my god", "o", "X")
"Xh my gXd"
32
return floor (6.8) return ceil (6.8)
6. 0 | 7. 0
33
return round (6.51) return round (6.49)
7 6
34
match (ator:Person)-[papel:ACTED_IN]->(filme:Movie) return toUpper(ator.name) as NOME, round(avg(papel.earnings)) as AverageEarnings order by AverageEarnings desc limit 1
retorna o ator com a melhor média de ganhos por filme
35
create (cat:Cat:Animal{"eats":"Birds","sound":"Meow"})
cria o node "cat", que é tanto um Cat quanto um Animal, que eats birds e sound Meow
36
create (cat:Cat{name: "Fluffy"})-[:grooms]->(cat)
cria um gato chamado Fluffy que grooms com ele mesmo
37
create (joe:Bunny:Animal{name: "Joe Bunny"}), | sarah:Bunny:Animal{name: "Sarah Bunny"}
cria um coelho chamado Joe Bunny e outro chamado Sarah Bunny
38
match (joe:Bunny{name: "Joe Bunny"}), (sarah:Bunny{name: "Sarah Bunny"}) merge (joe)-[:loves]->(sarah)
cria um nodo em que joe ama sarah se já existe não cria, porque é MERGE e não CREATE (que duplicaria)
39
match (node)-[rel]-() | delete node, rel
Deleta tudo, exceto node sem relationship nenhuma
40
match (x)-[y]-() delete x, y match (x) delete x ``` match (x) optional match (x)-[y]-() delete x, y ``` match (x) detach delete x
Deleta tudo, exceto node sem relationship nenhuma Deleta node sem relação Deleta tudo mesmo Deleta tudo mesmo (mesma coisa)
41
match(tom:Person{name:"Tom Hanks"}), (other)-[contato:HAS_CONTACT]->(tom) delete contato
Deleta o contato de Tom Hanks em todas as pessoas que têm
42
``` optional match (filme:Movie{title: "The Da Vinci Code"}) detach delete filme ```
Exclui esse filme da database e todas suas relações
43
match (tom:Person{name: "Tom Hanks"}) set tom:Hansome, tom.sex = "male" return tom
acrescenta sex male pro tom hanks e novo Label (tipo) de Handsome
44
match (tom:Person{name: "Tom Hanks"}) remove tom.sex return tom
remove a propriedade sex do tom hanks
45
match (tom:Person{name: "Tom Hanks"}) remove tom:Handsome return tom
Remove o label Handsome (Person é um label por exemplo)
46
match (tom:Person{name: "Tom Hanks"})-[:HAS_CONTACT]->(contact) with tom, count(contact) as cont set tom.contatinhos = cont return tom
adiciona uma propriedade com o numero de contatos do tom
47
CHANGING RELATIONSHIP TYPES ``` match (x:Person{name: "Tom Hanks"})-[antiga:HAS_CONTACT]->(y:Person{name: "Halle Berry" }) create (x)-[nova:OLD_CONTACT]->(y) set nova = antiga delete antiga return x, y ```
cria uma nova relação mantendo todas as propriedades da antiga, apaga a antiga
48
match (ator:Person)-[papel:ACTED_IN]->(filme:Movie) with ator, sum(papel.earnings) as Bufunfa where Bufunfa>=50000000 set ator:Rich, ator.Dindin = Bufunfa return ator.name, ator.Dindin
Retorna os atores que ja ganharam mais de 50 milhoes na soma de todos os filmes que fizeram
49
match (ator:Person:Rich) | remove ator:Rich, ator.Dindin
Deleta o label Rich e a propriedade Dindin de todos na database
50
null | empty
Sem a propriedade solicitada (Undefined) Propriedade presente mas vazia { }
51
with (true or false) as resulta return result with (true or null) as result return result with (false or null) as result return result with (true and null) as result return result with (false and null) as result return result with (null in [1,2,3,null]) as result return result with (null = null) as result return result with (null is null) as result return result
true true null (undefined) null (undefined) false null (undefined) - não sabemos se é o mesmo null null (undefined) - não sabemos se é o mesmo null true ! ! !
52
Supondo que não existe nenhum endereço cadastrado para Persons: match (x:Person) where x.adress is null return x match (x:Person) where x.adress = null return x
Returns all Persons Returns "null"
53
match (pessoa:Person) with (['Address 1', 'Address 2'] + [pessoa.address]) as partyDestinations return [address in partyDestinations where address is not null | address] as Destino
Retorna só address 1 e 2, sem o null
54
merge (lily:Person{name: 'Lily James'}) | return lily
merge = match or create (if exists: match, if not: create) ``` merge ...Person... merge ...Movie... merge () - [] -> () set propertie 1 set propertie 2 return x ```
55
merge (local:Location{name: "San Francisco"}) on create set local.criadoEm = timestamp(), local.criadoPor = "Artur Faria" return local merge (local:Location{name: "San Francisco"}) on match set local.test = "Troll" return local merge (local:Location{name: "San Francisco"}) on match set local.test = "Troll" return local
Suponha que não existe o Location San Francisco, cria ele com as propriedades criadoEm e criadoPor Mas por causa de "on create", se executar o segundo comando, não será criada a nova propriedade No terceiro vai atualizar com a nova propriedade,
56
... x.y = (x.y + 1) ...
vai adicionar +1 na propriedade a cada atualização do valor
57
``` merge (k:Person{name: "Keanu Reeves"}) merge (t:Movie{title: "Top Gun"}) merge (k)-[w:WATCH]->(t) on create set w.times = 1 on match set w.times = w.times + 1 return k, w, t ```
Conta quantas vezes e cada vez que o comando é executado aumente em 1, o numero de vezes que Keanu assistiu Top Gun
58
match (k:Person{name: "Keanu Reeves"})-[:HAS_CONTACT]->(c1)-[:HAS_CONTACT]->(c2) return k, c2 limit 1 match path=((k:Person{name: "Keanu Reeves"})-[:HAS_CONTACT]->(c1)-[:HAS_CONTACT]->(c2)) return path limit 1 match path=((k:Person{name: "Keanu Reeves"})-[:HAS_CONTACT*2]->(c2)) return path limit 1
retorna só o k e c2 retorna o c1 tambem sinonimo do anterior
59
return nodes(x) return relationships(x)
retorna só nodos retorna só relaçòes?
60
match (k:Person{name: "Keanu Reeves"})-[:HAS_CONTACT*2..4]->(c) return c
retorna os contatos que são no mínimo de 2o e no máximo de 4o grau 0 é o próprio k
61
``` match (k:Person{name: "Keanu Reeves"}) match (t:Person{name: "Tom Cruise"}) match path=((k)-[:HAS_CONTACT*]->(t)) return length(path) ```
retorna o número de paths entre k e t, mas não necessariamente o menor caminho
62
``` match (k:Person{name: "Keanu Reeves"}) match (t:Person{name: "Tom Cruise"}) match path = shortestPath((k)-[:HAS_CONTACT*..30]->(t)) return length(path) ``` match (k:Person{name: "Keanu Reeves"}) match (t:Person{name: "Tom Cruise"}) match path = allShortestPaths((k)-[:HAS_CONTACT*..30]->(t)) return path, length(path) as path_length
Retorna um único caminho mais curto (não retorna mais de um se ambos são o menor path possível) allShortestPaths retorna todos os mínimos
63
match (m:Person)-[:ACTED_IN]->(:Movie{title: "The Matrix"}) match (t:Person)-[:ACTED_IN]->(:Movie{title: "Top Gun"}) match path = allShortestPath((m)-[:HAS_CONTACT*..30]->(t)) return path
retorna caminho de contato entre atores de matrix e top gun