Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Базы данных - лекция11 - Neo4j (СУБД на основе графов)

Anton
November 20, 2018

Базы данных - лекция11 - Neo4j (СУБД на основе графов)

Anton

November 20, 2018
Tweet

More Decks by Anton

Other Decks in Education

Transcript

  1. Базы данных на основе графов • OrientDB.com (гибрид документоориентированной б/д

    + графы, поддерживает SQL) • Neo4j.com • Язык запросов Gremlin
  2. Модель данных • Вершина (node): основной элемент структуры • Отношение

    (relationship): направленное ребро, связывает две вершины • Свойства (properties) (для вершин и ребер): ключ- значение, можно ограничивать и индексировать • Метка (label): тип вершины или ребра (одна или несколько), разбивают вершины и ребра на группы, проиндексированы и оптимизированы
  3. Установка • neo4j.com, github.com/neo4j/neo4j • neo4j.com/download/ • > download neo4j

    server > Neo4j Repositories • debian.neo4j.org • Developers > Docs > Operations manual > Installation • neo4j.com/docs/operations-manual/current/installation/
  4. Установка: Ubuntu/Debian • wget -O - https://debian.neo4j.org/neotechnology.gpg.key | sudo apt-key

    add - • echo 'deb https://debian.neo4j.org/repo stable/' | sudo tee /etc/apt/sources.list.d/neo4j.list • sudo apt-get update • sudo apt-get install neo4j • /etc/init.d/neo4j start [stop/restart]
  5. Задача-1: сменить исходный пароль • Имя пользователя по умолчанию: neo4j

    • Пароль по умолчанию: neo4j • Пароль придется сразу сменить • Старый пароль оставить не получится • Выставим здесь новый пароль: neo4jj
  6. Вариант-1: веб-консоль localhost:7474/browser/ При первом запуске сразу после установки: •

    открыть страницу в браузере, • выставить новый пароль (например: neo4jj) • TODO: отскриншотить
  7. Cypher shell neo4j.com/docs/operations-manual/current/ tools/cypher-shell/ $ cypher-shell username: neo4j password: ******

    [neo4jj — задали после установки] Connected to Neo4j 3.3.1 at bolt://localhost:7687 as user neo4j. Type :help for a list of available commands or :exit to exit the shell. Note that Cypher queries must end with a semicolon.
  8. Developer manual neo4j.com/docs/developer-manual/current/ • Chapter 2. Get started > Get

    started with Cypher neo4j.com/docs/developer-manual/current/ get-started/cypher/ • Chapter 3. Cypher neo4j.com/docs/developer-manual/current/ cypher/
  9. Создать фильм, двух актеров, • CREATE (TheMatrix:Movie {title:'The Matrix', released:1999,

    tagline:'Welcome to the Real World'}) • CREATE (Keanu:Person {name:'Keanu Reeves', born:1964}) • CREATE (Carrie:Person {name:'Carrie-Anne Moss', born:1967}) • […] (мы еще не закончили)
  10. • Уточняющие имена вершин при создании (TheMatrix, Keanu, Carrie) действуют

    только внутри одного составного запроса, состоящего из нескольких команд, — до точки с запятой. • После точки с запятой эти именованные ссылки действовать не будут.
  11. Показать все вершины MATCH (nodes) RETURN nodes LIMIT 10; +--------------------------------------------------------------------------------------+

    | nodes | +--------------------------------------------------------------------------------------+ | (:Movie {tagline: "Welcome to the Real World", title: "The Matrix", released: 1999}) | | (:Person {name: "Keanu Reeves", born: 1964}) | | (:Person {name: "Carrie-Anne Moss", born: 1967}) | +--------------------------------------------------------------------------------------+
  12. Только люди (фильтр по метке) MATCH (people:Person) RETURN people.name LIMIT

    10; +--------------------+ | people.name | +--------------------+ | "Carrie-Anne Moss" | | "Keanu Reeves" | +--------------------+ 2 rows available after 1 ms, consumed after another 2 ms
  13. Только фильмы (фильтр по метке) MATCH (movies:Movie) RETURN movies.title LIMIT

    10; +--------------+ | movies.title | +--------------+ | "The Matrix" | +--------------+ 1 row available after 35 ms, consumed after another 1 ms
  14. Поиск по свойствам по всем вершинам MATCH (keanu {name: "Keanu

    Reeves"}) RETURN keanu; +----------------------------------------------+ | keanu | +----------------------------------------------+ | (:Person {born: 1964, name: "Keanu Reeves"}) | +----------------------------------------------+
  15. По вершинам с уточнением типа MATCH (keanu:Person {name: "Keanu Reeves"})

    RETURN keanu; +----------------------------------------------+ | keanu | +----------------------------------------------+ | (:Person {born: 1964, name: "Keanu Reeves"}) | +----------------------------------------------+
  16. Составное условие MATCH (nineties:Movie) WHERE nineties.released >= 1990 AND nineties.released

    < 2000 RETURN nineties.title; +----------------+ | nineties.title | +----------------+ | "The Matrix" | +----------------+ 1 row available after 41 ms, consumed after another 6 ms
  17. Поиск отношений MATCH (keanu:Person {name: "Keanu Reeves"})- [:ACTED_IN]->(keanuMovies) RETURN keanu,

    keanuMovies; +-------------------------------------------------------------------------------------------------------------------------------------+ | keanu | keanuMovies | +-------------------------------------------------------------------------------------------------------------------------------------+ | (:Person {born: 1964, name: "Keanu Reeves"}) | (:Movie {tagline: "Welcome to the Real World", title: "The Matrix", released: 1999}) | +-------------------------------------------------------------------------------------------------------------------------------------+
  18. Neo4j + NodeJS neo4j.com/developer/javascript/ • npm install neo4j-driver • neo4j.com/developer/example-project/

    • github.com/neo4j-examples • github.com/neo4j-examples/movies-javascript-bolt • github.com/neo4j-examples/movies-javascript- bolt/blob/master/src/neo4jApi.js
  19. node-neo4j-create.js var neo4j = require("neo4j-driver").v1; var uri = "bolt://localhost"; var

    user = "neo4j"; var password = "neo4jj"; var driver = neo4j.driver(uri, neo4j.auth.basic(user, password)); var session = driver.session(); [...]
  20. node-neo4j-create.js session.run( "CREATE (TheMatrix:Movie {title:'The Matrix', released:1999, tagline:'Welcome to the

    Real World'}) " + "CREATE (Keanu:Person {name:'Keanu Reeves', born:1964}) " + "CREATE (Carrie:Person {name:'Carrie-Anne Moss', born:1967}) " + "CREATE " + "(Keanu)-[:ACTED_IN {roles:['Neo']}]->(TheMatrix)," + "(Carrie)-[:ACTED_IN {roles:['Trinity']}]->(TheMatrix);" ).then(result => { session.close(); // on application exit: driver.close(); });
  21. node-neo4j-create.js const personName = "Alice"; session.run( "CREATE (a:Person {name: $name})

    RETURN a", {name: personName} ).then(result => { session.close(); const singleRecord = result.records[0]; // const node = singleRecord.get("a"); const node = singleRecord.get(0); console.log(node.properties.name); // on application exit: driver.close(); });
  22. node-neo4j.js session.run( "MATCH (people:Person) RETURN people LIMIT 10;" ).then(result =>

    { session.close(); console.log("Got records: " + result.records.length); for(var i = 0; i < result.records.length; i++) { var record = result.records[i]; //var node = record.get(0); var node = record.get("people"); console.log(node.properties.name); } // on application exit: driver.close(); });