0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

グラフデータベースneo4jでWEBスクレイピングをしてみた。

Last updated at Posted at 2021-10-23

  • 読みとるHTMLページについて

ベルギーのBeerGraphをWikipediaのHTMLページから直接読み込む方法がブログにあったので試してみました。
image.png

neo4jのpluginであるapoc.load.html機能を使って、中間ステップを経ずにHTMLページから直接データを自動的にインポートします。

APOCではHTMLページから直接読み込むことができます。
APOCは、Cypher言語から呼び出されるユーティリティー関数とプロシージャの非常に柔軟で拡張可能な実用的なセットです。
apoc.load.htmlというプロシージャを使うと、インターネット上の特定のHTMLページを呼び出し、その内容を読み取って、
後続のcypher文でその内容を処理することができます。

このプロシージャの構文です。

apoc.load.html(url :: STRING?, query = {} :: MAP?, config = {} :: MAP?) :: (value :: MAP?)

実際にはURL、クエリのセット、設定パラメータ(もしあれば)が必要になります。

  • データベースの作成

まずNeo4jにデータベースを作成します。

create database beergraph;

次に、新しいCypher構文を使用して、データベースのインデックスを設定します。

CREATE INDEX beerbrand_name FOR (bb:BeerBrand) ON (bb.name);
CREATE INDEX brewery_name FOR (br:Brewery) ON (br.name);
CREATE INDEX beertype_name FOR (bt:BeerType) ON (bt.name);
CREATE INDEX alcoholpercentage_value FOR (ap:AlcoholPercentage) ON (ap.value);

これができたら、次のクエリを使ってWikipediaのページからデータベースに直接インポートすることができます。

WITH "https://nl.wikipedia.org/wiki/Lijst_van_Belgische_bieren" as url
CALL apoc.load.html(url, {
brand: "table.wikitable tbody tr td:eq(0)",
beertype: "table.wikitable tbody tr td:eq(1)",
alcoholpercentage: "table.wikitable tbody tr td:eq(2)",
brewery: "table.wikitable tbody tr td:eq(3)",
timeframe: "table.wikitable tbody tr td:eq(4)"
}) yield value
WITH value, size(value.brand) as rangeup
UNWIND range(0,rangeup) as i
WITH value.brand[i].text as BeerBrand, value.brewery[i].text as Brewery, value.alcoholpercentage[i].text as AlcoholPercentage, value.beertype[i].text as BeerType, value.timeframe[i].text as Timeframe
MERGE (bt:BeerType {name: coalesce(BeerType,"Unknown")})
MERGE (bb:BeerBrand {name: coalesce(BeerBrand,"Unknown")})
SET bb.Timeframe = coalesce(Timeframe,"Unknown")
MERGE (br:Brewery {name: coalesce(Brewery,"Unknown")})
MERGE (ap:AlcoholPercentage {value: coalesce(AlcoholPercentage,"Unknown")})
MERGE (bb)-[:HAS_ALCOHOLPERCENTAGE]->(ap)
MERGE (bb)-[:IS_A]->(bt)
MERGE (bb)<-[:BREWS]-(br);

3,000個のノードと6,000個の関係をインポートができました。

ベルギーのビアグラフです。
image.png

ベルギーはビールの数が多いのですね。
image.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?