QGISでは、SQL風の式の構文解析のためのいくつかサポートしています。SQL構文の小さなサブセットのみがサポートされています。式は、ブール述語(TrueまたはFalseを返す)として、または関数(スカラー値を返す)のどちらかとして評価できます。使用可能な関数の完全なリストについては、ユーザーマニュアル中の 式 を参照。
3つの基本的な種別がサポートされています:
数値 — 実数及び10進数。例. 123
, 3.14
文字列 — シングルクオートで囲む必要があります: 'hello world'
カラム参照 — 評価する際に、参照は項目の実際の値で置き換えられます。名前はエスケープされません。
次の演算子が利用可能です:
算術演算子: +
, -
, *
, /
, ^
丸括弧: 演算を優先します: (1 + 1) * 3
単項のプラスとマイナス: -12
, +5
数学的ファンクション: sqrt
, sin
, cos
, tan
, asin
, acos
, atan
変換関数: `` to_int``、 `` to_real``、 `` to_string``、 `` to_date``
ジオメトリファンクション: $area
, $length
ジオメトリ処理関数: `` $ x``、 `` $のy``、 `` $のgeometry``、 `` num_geometries``、 `` centroid``
以下の記述がサポートされています:
比較: =
, !=
, >
, >=
, <
, <=
パターンマッチング: LIKE
(% と _ を使用), ~
(正規表現)
論理記述: AND
, OR
, NOT
NULL 値チェック: IS NULL
, IS NOT NULL
記法例:
1 + 2 = 3
sin(angle) > 0
'Hello' LIKE 'He%'
(x > 10 AND y > 10) OR z = 0
スカラー表現の例:
2 ^ 10
sqrt(val)
$length + 1
>>> exp = QgsExpression('1 + 1 = 2')
>>> exp.hasParserError()
False
>>> exp = QgsExpression('1 + 1 = ')
>>> exp.hasParserError()
True
>>> exp.parserErrorString()
PyQt4.QtCore.QString(u'syntax error, unexpected $end')
次の例は機能に対して与えられた表現を評価しています。”Column” はレイヤ内の項目名です。
>>> exp = QgsExpression('Column = 99')
>>> value = exp.evaluate(feature, layer.pendingFields())
>>> bool(value)
True
複数の地物をチェックする必要がある場合は、 QgsExpression.prepare() も使うことができます。 QgsExpression.prepare() を使うと、実行の評価速度を向上できます。
>>> exp = QgsExpression('Column = 99')
>>> exp.prepare(layer.pendingFields())
>>> value = exp.evaluate(feature)
>>> bool(value)
True
次の例はレイヤをフィルタリングして記法にマッチする任意の地物を返却します。
def where(layer, exp):
print "Where"
exp = QgsExpression(exp)
if exp.hasParserError():
raise Exception(exp.parserErrorString())
exp.prepare(layer.pendingFields())
for feature in layer.getFeatures():
value = exp.evaluate(feature)
if exp.hasEvalError():
raise ValueError(exp.evalErrorString())
if bool(value):
yield feature
layer = qgis.utils.iface.activeLayer()
for f in where(layer, 'Test > 1.0'):
print f + " Matches expression"