QGISでは、SQL風の式の構文解析について少しサポートしています。サポートされるのはSQL構文の小さなサブセットのみです。式は、ブール述語(真または偽を返す)または関数(スカラー値を返す)のどちらかとして評価できます。使用可能な関数の完全なリストについては、ユーザーマニュアル中の 式 を参照。
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')
The following example will evaluate the given expression against a feature. “Column” is the name of the field in the layer.
>>> exp = QgsExpression('Column = 99')
>>> value = exp.evaluate(feature, layer.pendingFields())
>>> bool(value)
True
You can also use QgsExpression.prepare() if you need check more than one feature. Using QgsExpression.prepare() will increase the speed that evaluate takes to run.
>>> 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"