LoginSignup
9
8

More than 5 years have passed since last update.

curl で SPARQL

Posted at

curl で SPARQL Endpoint にリクエストを投げるパターンのおぼえがき。 SPARQL クライアントを使えない場合やバッチ処理の実行などに。

1. 基本

実行したい SPARQL Query をテキストファイルに保存して

sparql.rq
select * where {?s ?p ?o.} limit 10

以下のように実行して JSON Results を得る。

$ curl -H 'Accept: application/sparql-results+json' --data-urlencode 'query@-' http://dbpedia.org/sparql < sparql.rq
{
  "head": { "link": [], "vars": ["s", "p", "o"] },
  "results": { "distinct": false, "ordered": true, "bindings": 
    [{ "s": {...}, "p": {...}, "o": {...} }] 
  }
}

この方法は query via POST with URL-encoded parameters (SPARQL 1.1 Protocol) に準拠したエンドポイントを想定して POST リクエストを発行するものですが、query via GET の場合には以下のように -G オプションをつけることで GET リクエストを発行することも可能です。

$ curl -G -H 'Accept: application/sparql-results+json' --data-urlencode 'query@-' http://dbpedia.org/sparql < sparql.rq

2. 出力フォーマットの変更

  • -H 'Accept: xxxxxxxxxxxxx' の xxxxxx の部分を下の表の Content-Type で適宜置き換える
  • Accept ヘッダを省略した場合は Endpoint のデフォルトフォーマットで返ってくるはず
  • Endpoint は必ずしもすべての出力フォーマットに対応しているわけではないので注意
  • csv / tsv の場合は charset=UTF-8 のように出力エンコード指定も可能だが、Endpoint が対応していないことも
type Content-Type
json application/sparql-results+json
xml application/sparql-results+xml
csv text/csv
tsv text/tab-separated-values

3. クエリーの指定

インライン

  • 短いクエリーなら query=... のように直接 SPARQL を書いても OK
$ curl -H 'Accept: application/sparql-results+json' --data-urlencode 'query=select * where {?s ?p ?o.} limit 10' http://dbpedia.org/sparql

ファイル

  • --data-urlencode オプションに query@{filename} と指定すると query パラメータの値としてファイルの中身が展開される
  • 冒頭の query@- は標準入力を展開する、の意味
$ curl -H 'Accept: application/sparql-results+json' --data-urlencode 'query@sparql.rq' http://dbpedia.org/sparql

4. 参考

9
8
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
9
8