7.2. JSON属性¶
GeoMesa支持本地JSON与GeoTools数据存储的集成。简单功能 String -type属性可以标记为JSON,然后使用CQL进行查询。创建简单要素类型时必须指定JSON属性:
import org.locationtech.geomesa.utils.interop.SimpleFeatureTypes;
// append the json hint after the attribute type, separated by a colon
String spec = "json:String:json=true,dtg:Date,*geom:Point:srid=4326"
SimpleFeatureType sft = SimpleFeatureTypes.createType("mySft", spec);
dataStore.createSchema(sft);
JSON属性仍然是字符串,并被设置为任何其他字符串:
String json = "{ \"foo\" : \"bar\" }";
SimpleFeature sf = ...
sf.setAttribute("json", json);
可以使用JSONPath表达式查询JSON属性。路径的第一部分引用简单的功能属性名称,路径的其余部分应用于JSON属性。请注意,在ECQL中,路径表达式必须用双引号括起来。
Filter filter = ECQL.toFilter("\"$.json.foo\" = 'bar'")
SimpleFeature sf = ...
sf.setAttribute("json", "{ \"foo\" : \"bar\" }");
filter.evaluate(sf); // returns true
sf.getAttribute("\"$.json.foo\""); // returns "bar"
sf.setAttribute("json", "{ \"foo\" : \"baz\" }");
filter.evaluate(sf); // returns false
sf.getAttribute("\"$.json.foo\""); // returns "baz"
sf.getAttribute("\"$.json.bar\""); // returns null
7.2.1. JSONPath CQL过滤器函数¶
JSON属性可以包含句点和空格。为了通过ECQL过滤器查询这些属性,请使用jsonPath CQL过滤器函数。这会将路径传递给内部解释器函数,该函数了解如何处理这些属性名称。
Filter filter = ECQL.toFilter("jsonPath('$.json.foo') = 'bar'")
SimpleFeature sf = ...
sf.setAttribute("json", "{ \"foo\" : \"bar\" }");
filter.evaluate(sf); // returns true
要处理属性名称中的句号和空格,请用标准的方括号表示法将属性括起来。但是,由于路径将作为字符串文字参数传递给jsonPath函数,因此需要使用额外的单引号对单引号进行转义。
Filter filter = ECQL.toFilter("jsonPath('$.json.[''foo.bar'']') = 'bar'")
SimpleFeature sf = ...
sf.setAttribute("json", "{ \"foo.bar\" : \"bar\" }");
filter.evaluate(sf); // returns true
同样,空格也是如此:
Filter filter = ECQL.toFilter("jsonPath('$.json.[''foo bar'']') = 'bar'")
SimpleFeature sf = ...
sf.setAttribute("json", "{ \"foo bar\" : \"bar\" }");
filter.evaluate(sf); // returns true
7.2.2. 具有Geoserver样式的JSONPath¶
在Geoserver样式(SLD或CSS)中使用JSON路径时,必须分离属性和路径才能使GeoTools渲染器正常工作。在本例中,传入两个参数,第一个参数是JSON类型属性名称的双引号中的属性表达式,第二个参数是路径:
* {
mark: symbol(arrow);
mark-size: 12px;
mark-rotation: [ jsonPath("json", 'foo') ];
:mark {
fill: #009900;
}
}