Spring认证中国教育管理中心-Spring Data MongoDB教程五
发布于 3 年前 作者 tangqiang 1713 次浏览 来自 分享

原标题:Spring认证中国教育管理中心-Spring Data MongoDB教程五(内容来源:Spring中国教育管理中心)

11.6.5.GeoJSON 支持
MongoDB 支持GeoJSON和用于地理空间数据的简单(传统)坐标对。这些格式既可用于存储数据,也可用于查询数据。请参阅有关 GeoJSON 支持的MongoDB 手册以了解要求和限制。

域类中的 GeoJSON 类型
在域类中使用GeoJSON类型很简单。该
org.springframework.data.mongodb.core.geo包中包含的类型,如GeoJsonPoint,GeoJsonPolygon和其他。这些类型是对现有org.springframework.data.geo类型的扩展。以下示例使用了一个GeoJsonPoint:

public class Store {

String id;

/**
 * location is stored in GeoJSON format.
 * {
 *   "type" : "Point",
 *   "coordinates" : [ x, y ]
 * }
 */
GeoJsonPoint location;

}
Spring认证中国教育管理中心-Spring Data MongoDB教程五
存储库查询方法中的 GeoJSON 类型
使用 GeoJSON 类型作为存储库查询参数会$geometry在创建查询时强制使用运算符,如以下示例所示:

public interface StoreRepository extends CrudRepository<Store, String> {

List&lt;Store&gt; findByLocationWithin(Polygon polygon);  

}

/*

  • {
  • “location”: {
    "$geoWithin": {
      "$geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [-73.992514,40.758934],
            [-73.961138,40.760348],
            [-73.991658,40.730006],
            [-73.992514,40.758934]
          ]
        ]
      }
    }
  • }
  • }
    */
    repo.findByLocationWithin(
    new GeoJsonPolygon(
    new Point(-73.992514, 40.758934),
    new Point(-73.961138, 40.760348),
    new Point(-73.991658, 40.730006),
    new Point(-73.992514, 40.758934)));

/*

  • {
  • “location” : {
    "$geoWithin" : {
       "$polygon" : [ [-73.992514,40.758934] , [-73.961138,40.760348] , [-73.991658,40.730006] ]
    }
  • }
  • }
    */
    repo.findByLocationWithin(
    new Polygon(
    new Point(-73.992514, 40.758934),
    new Point(-73.961138, 40.760348),
    new Point(-73.991658, 40.730006)));
    Spring认证中国教育管理中心-Spring Data MongoDB教程五
    使用 commons 类型的存储库方法定义允许使用 GeoJSON 和遗留格式调用它。

使用 GeoJSON 类型来使用$geometry运算符。

请注意,GeoJSON 多边形需要定义一个封闭的环。

使用旧格式$polygon运算符。

度量和距离计算
然后 MongoDB$geoNear运算符允许使用 GeoJSON Point 或旧坐标对。

NearQuery.near(new Point(-73.99171, 40.738868))
{
"$geoNear": {
//…
“near”: [-73.99171, 40.738868]
}
}
NearQuery.near(new GeoJsonPoint(-73.99171, 40.738868))
{
"$geoNear": {
//…
“near”: { “type”: “Point”, “coordinates”: [-73.99171, 40.738868] }
}
}
尽管在语法上有所不同,但无论集合中的目标 Document 使用什么格式,服务器都可以接受。

*距离计算存在巨大差异。使用旧格式对地球上的弧度进行操作,如球体,而 GeoJSON 格式使用Meters。

为避免严重的头痛,请确保将 设置Metric为所需的测量单位,以确保正确计算距离。

换句话说:

假设您有 5 个文件,如下所示:

{
"_id" : ObjectId(“5c10f3735d38908db52796a5”),
“name” : “Penn Station”,
“location” : { “type” : “Point”, “coordinates” : [ -73.99408, 40.75057 ] }
}
{
"_id" : ObjectId(“5c10f3735d38908db52796a6”),
“name” : “10gen Office”,
“location” : { “type” : “Point”, “coordinates” : [ -73.99171, 40.738868 ] }
}
{
"_id" : ObjectId(“5c10f3735d38908db52796a9”),
“name” : “City Bakery “,
“location” : { “type” : “Point”, “coordinates” : [ -73.992491, 40.738673 ] }
}
{
”_id” : ObjectId(“5c10f3735d38908db52796aa”),
“name” : “Splash Bar”,
“location” : { “type” : “Point”, “coordinates” : [ -73.992491, 40.738673 ] }
}
{
"_id" : ObjectId(“5c10f3735d38908db52796ab”),
“name” : “Momofuku Milk Bar”,
“location” : { “type” : “Point”, “coordinates” : [ -73.985839, 40.731698 ] }
}
Spring认证中国教育管理中心-Spring Data MongoDB教程五
[-73.99171, 40.738868]使用 GeoJSON获取 400 米半径内的所有文档如下所示:

示例 77. GeoNear 和 GeoJSON

{
"$geoNear": {
“maxDistance”: 400,
“num”: 10,
“near”: { type: “Point”, coordinates: [-73.99171, 40.738868] },
“spherical”:true,
“key”: “location”,
“distanceField”: “distance”
}
}
返回以下 3 个文件:

{
"_id" : ObjectId(“5c10f3735d38908db52796a6”),
“name” : “10gen Office”,
“location” : { “type” : “Point”, “coordinates” : [ -73.99171, 40.738868 ] }
“distance” : 0.0
}
{
"_id" : ObjectId(“5c10f3735d38908db52796a9”),
“name” : “City Bakery “,
“location” : { “type” : “Point”, “coordinates” : [ -73.992491, 40.738673 ] }
“distance” : 69.3582262492474
}
{
”_id” : ObjectId(“5c10f3735d38908db52796aa”),
“name” : “Splash Bar”,
“location” : { “type” : “Point”, “coordinates” : [ -73.992491, 40.738673 ] }
“distance” : 69.3582262492474
}
到中心点的最大距离(以米为单位)。

GeoJSON 总是在一个球体上运行。

到中心点的距离(以米为单位)。

现在,当使用旧坐标对时,如前所述,对弧度进行操作。所以我们使用Metrics#KILOMETERS when constructing the `$geoNear命令。在Metric确保使乘数设置正确的距离。

示例 78.带有传统坐标对的 GeoNear

{
"$geoNear": {
“maxDistance”: 0.0000627142377,
“distanceMultiplier”: 6378.137,
“num”: 10,
“near”: [-73.99171, 40.738868],
“spherical”:true,
“key”: “location”,
“distanceField”: “distance”
}
}
像 GeoJSON 变体一样返回 3 个文档:

{
"_id" : ObjectId(“5c10f3735d38908db52796a6”),
“name” : “10gen Office”,
“location” : { “type” : “Point”, “coordinates” : [ -73.99171, 40.738868 ] }
“distance” : 0.0
}
{
"_id" : ObjectId(“5c10f3735d38908db52796a9”),
“name” : “City Bakery “,
“location” : { “type” : “Point”, “coordinates” : [ -73.992491, 40.738673 ] }
“distance” : 0.0693586286032982
}
{
”_id” : ObjectId(“5c10f3735d38908db52796aa”),
“name” : “Splash Bar”,
“location” : { “type” : “Point”, “coordinates” : [ -73.992491, 40.738673 ] }
“distance” : 0.0693586286032982
}
到中心点的最大距离(以弧度为单位)。

距离乘数所以我们得到公里作为结果距离。

确保我们对 2d_sphere 索引进行操作。

距离中心点的距离以公里为单位- 乘以 1000 以匹配GeoJSON 变体的米。

GeoJSON 杰克逊模块
通过使用Web 支持,Spring Data 将额外的 Jackson 注册Modules到ObjectMapper用于反/序列化常见 Spring Data 域类型。请参阅Spring Data Jackson Modules部分以了解有关此功能的基础架构设置的更多信息。

MongoDB 模块JsonDeserializer通过GeoJsonConfiguration公开GeoJsonModule.

org.springframework.data.mongodb.core.geo.GeoJsonPoint
org.springframework.data.mongodb.core.geo.GeoJsonMultiPoint
org.springframework.data.mongodb.core.geo.GeoJsonLineString
org.springframework.data.mongodb.core.geo.GeoJsonMultiLineString
org.springframework.data.mongodb.core.geo.GeoJsonPolygon
org.springframework.data.mongodb.core.geo.GeoJsonMultiPolygon
该GeoJsonModule只注册JsonDeserializer小号!
要ObjectMapper为JsonSerializers配备一组对称的s,您需要为 手动配置这些 sObjectMapper或提供作为 Spring
BeanSpringDataJacksonModules公开的自定义配置GeoJsonModule.serializers()。

class GeoJsonConfiguration implements SpringDataJacksonModules {

[@Bean](/user/Bean)
public Module geoJsonSerializers() {
	return GeoJsonModule.serializers();
}

}
下一个主要版本 ( 4.0) 将默认为 GeoJSON 类型注册JsonDeserializers 和JsonSerializers 。

11.6.6.全文查询
从 MongoDB 2.6 版开始,您可以使用$text运算符运行全文查询。方法和操作具体到全文查询是可用的TextQuery和TextCriteria。进行全文搜索时,请参阅MongoDB 参考以了解其行为和限制。

全文检索
在实际使用全文搜索之前,您必须正确设置搜索索引。有关如何创建索引结构的更多详细信息,请参阅文本索引。以下示例显示了如何设置全文搜索:

db.foo.createIndex(
{
title : “text”,
content : “text”
},
{
weights : {
title : 3
}
}
)
coffee cake可以按如下方式定义和运行查询搜索:

例 79.全文查询

Query query = TextQuery
.queryText(new TextCriteria().matchingAny(“coffee”, “cake”));

List<Document> page = template.find(query, Document.class);
根据weights用途按相关性对结果进行排序TextQuery.sortByScore。

示例 80. 全文查询 - 按分数排序

Query query = TextQuery
.queryText(new TextCriteria().matchingAny(“coffee”, “cake”))
.sortByScore()
.includeScore();

List<Document> page = template.find(query, Document.class);
使用 score 属性按触发的相关性对结果进行排序.sort({‘score’: {’$meta’: ‘textScore’}})。

用于TextQuery.includeScore()在结果中包含计算出的相关性Document。

您可以通过在搜索词前加上-或使用来排除搜索词,notMatching如下例所示(请注意,这两行具有相同的效果,因此是多余的):

// search for ‘coffee’ and not 'cake’
TextQuery.queryText(new TextCriteria().matching(“coffee”).matching("-cake"));
TextQuery.queryText(new TextCriteria().matching(“coffee”).notMatching(“cake”));
TextCriteria.matching按原样使用提供的术语。因此,您可以通过将短语放在双引号之间来定义短语(例如,“coffee cake”)或使用 byTextCriteria.phrase.下面的示例显示了定义短语的两种方式:

// search for phrase 'coffee cake’
TextQuery.queryText(new TextCriteria().matching("“coffee cake”"));
TextQuery.queryText(new TextCriteria().phrase(“coffee cake”));
您可以使用 上的相应方法为$caseSensitive和设置标志。请注意,这两个可选标志已在 MongoDB 3.2 中引入,除非明确设置,否则不会包含在查询中。$
diacriticSensitiveTextCriteria

11.6.7.校对
从 3.4 版本开始,MongoDB 支持用于集合和索引创建以及各种查询操作的排序规则。排序规则根据ICU 排序规则定义字符串比较规则。归类文档由封装在 中的各种属性组成Collation,如下面的清单所示:

Collation collation = Collation.of(“fr”)

.strength(ComparisonLevel.secondary()
.includeCase())

.numericOrderingEnabled()

.alternate(Alternate.shifted().punct())

.forwardDiacriticSort()

.normalizationEnabled();
Collation创建时需要语言环境。这可以是语言环境的字符串表示形式,a Locale(考虑语言、国家和变体)或CollationLocale. 创建时必须使用语言环境。

整理强度定义了表示字符之间差异的比较级别。您可以根据所选强度配置各种选项(区分大小写、大小写排序等)。

指定是将数字字符串作为数字还是作为字符串进行比较。

指定排序规则是否应将空格和标点符号视为基本字符以进行比较。

指定带有变音符号的字符串是否从字符串的后面排序,例如使用某些法语词典排序。

指定是否检查文本是否需要归一化以及是否进行归一化。

排序规则可用于创建集合和索引。如果您创建一个指定排序规则的集合,除非您指定不同的排序规则,否则该排序规则将应用于索引创建和查询。排序规则对整个操作有效,不能在每个字段的基础上指定。

与其他元数据一样,排序规则可以通过 注释的collation属性从域类型派生@Document,并将在运行查询、创建集合或索引时直接应用。

当 MongoDB 在第一次交互时自动创建集合时,将不会使用带注释的排序规则。这将需要额外的商店交互延迟整个过程。请
MongoOperations.createCollection在这些情况下使用。

Collation french = Collation.of(“fr”); Collation german = Collation.of(“de”); template.createCollection(Person.class, CollectionOptions.just(collation)); template.indexOps(Person.class).ensureIndex(new Index(“name”, Direction.ASC).collation(german));

如果未指定排序规则 ( Collation.simple()),MongoDB 将使用简单的二进制比较。

对集合操作使用排序规则是Collation在查询或操作选项中指定实例的问题,如以下两个示例所示:

示例 81. 使用排序规则与 find

Collation collation = Collation.of(“de”);

Query query = new Query(Criteria.where(“firstName”).is(“Amél”)).collation(collation);

List<Person> results = template.find(query, Person.class);
示例 82.使用排序规则与 aggregate

Collation collation = Collation.of(“de”);

AggregationOptions options = AggregationOptions.builder().collation(collation).build();

Aggregation aggregation = newAggregation(
project(“tags”),
unwind(“tags”),
group(“tags”)
.count().as(“count”)
).withOptions(options);

AggregationResults<TagCount> results = template.aggregate(aggregation, “tags”, TagCount.class);
仅当用于操作的排序规则与索引排序规则匹配时才使用索引。

MongoDB RepositoriesCollations通过注解的collation属性支持@Query

示例 83. 对存储库的整理支持

public interface PersonRepository extends MongoRepository<Person, String> {

@Query(collation = “en_US”)
List<Person> findByFirstname(String firstname);

@Query(collation = “{ ‘locale’ : ‘en_US’ }”)
List<Person> findPersonByFirstname(String firstname);

@Query(collation = “?1”)
List<Person> findByFirstname(String firstname, Object collation);

@Query(collation = “{ ‘locale’ : ‘?1’ }”)
List<Person> findByFirstname(String firstname, String collation);

List<Person> findByFirstname(String firstname, Collation collation);

@Query(collation = “{ ‘locale’ : ‘en_US’ }”)
List<Person> findByFirstname(String firstname, @Nullable Collation collation);
}
静态归类定义导致{ ‘locale’ : ‘en_US’ }.

静态归类定义导致{ ‘locale’ : ‘en_US’ }.

动态整理取决于第二个方法参数。允许的类型包括String(eg. ‘en_US’), Locacle(eg. Locacle.US) 和Document(eg. new Document(“locale”, “en_US”))

动态整理取决于第二个方法参数。

将Collation方法参数应用于查询。

该Collation方法的参数覆盖默认collation的@Query,如果不为空。

如果您为存储库查找器方法启用了自动索引创建,则在创建索引时将包括潜在的静态排序规则定义,如 (1) 和 (2) 所示。

最Collation具体的 outroules 可能定义了其他的 outroules。这意味着方法参数超过查询方法注释超过 doamin 类型注释。

JSON 架构
从 version 3.6 开始,MongoDB 支持根据提供的JSON Schema验证文档的集合。创建集合时可以定义架构本身以及验证操作和级别,如以下示例所示:

示例 84.示例 JSON 模式

{
“type”: “object”,

“required”: [ “firstname”, “lastname” ],

“properties”: {

"firstname": {                                                         
  "type": "string",
  "enum": [ "luke", "han" ]
},
"address": {                                                           
  "type": "object",
  "properties": {
    "postCode": { "type": "string", "minLength": 4, "maxLength": 5 }
  }
}

}
}
JSON 模式文档总是从其根开始描述整个文档。模式是模式对象本身,它可以包含描述属性和子文档的嵌入模式对象。

required是描述文档中需要哪些属性的属性。它可以与其他模式约束一起选择指定。请参阅有关可用关键字的MongoDB 文档。

properties与描述object类型的模式对象相关。它包含特定于属性的架构约束。

firstname为firsname文档内的字段指定约束。在这里,它是一个基于字符串的properties元素,用于声明可能的字段值。

address是为其postCode字段中的值定义架构的子文档。

您可以通过指定模式文档(即,通过使用DocumentAPI 解析或构建文档对象)或使用 Spring Data 的 JSON 模式实用程序构建它来提供模式
org.springframework.data.mongodb.core.schema。MongoJsonSchema是所有与 JSON 模式相关的操作的入口点。以下示例显示了如何使用MongoJsonSchema.builder()创建 JSON 模式:

示例 85.创建一个 JSON 模式

MongoJsonSchema.builder()
.required(“lastname”)

.properties(
            required(string("firstname").possibleValues("luke", "han")), 

            object("address")
                 .properties(string("postCode").minLength(4).maxLength(5)))

.build();                                        

获取模式构建器以使用流畅的 API 配置模式。

直接配置所需的属性,如此处所示,或使用更多详细信息如 3 所示。

配置所需的字符串类型firstname字段,仅允许luke和han值。属性可以是有类型的或无类型的。使用静态导入JsonSchemaProperty使语法稍微紧凑一些并获得入口点,例如string(…).

构建架构对象。使用模式创建集合或查询文档。

已经有一些预定义和强类型模式对象(JsonSchemaObject和JsonSchemaProperty)通过网关接口上的静态方法可用。但是,您可能需要构建自定义属性验证规则,可以通过构建器 API 创建,如下例所示:

// “birthdate” : { “bsonType”: “date” }
JsonSchemaProperty.named(“birthdate”).ofType(Type.dateType());

// “birthdate” : { “bsonType”: “date”, “description”, “Must be a date” }
JsonSchemaProperty.named(“birthdate”).with(JsonSchemaObject.of(Type.dateType()).description(“Must be a date”));
CollectionOptions 为集合提供架构支持的入口点,如以下示例所示:

示例 86.创建集合 $jsonSchema

MongoJsonSchema schema = MongoJsonSchema.builder().required(“firstname”, “lastname”).build();

template.createCollection(Person.class, CollectionOptions.empty().schema(schema));
生成模式
设置模式可能是一项耗时的任务,我们鼓励每个决定这样做的人真正花时间。重要的是,架构更改可能很困难。然而,有时人们可能不想拒绝它,这就是JsonSchemaCreator发挥作用的地方。

JsonSchemaCreator它的默认实现会生成MongoJsonSchema映射基础结构提供的域外类型元数据。这意味着,会考虑带注释的属性以及潜在的自定义转换。

例 87.从域类型生成 Json Schema

public class Person {

private final String firstname;                   
private final int age;                            
private Species species;                          
private Address address;                          
private @Field(fieldType=SCRIPT) String theForce; 
private [@Transient](/user/Transient) Boolean useTheForce;           

public Person(String firstname, int age) {         

    this.firstname = firstname;
    this.age = age;
}

// gettter / setter omitted

}

MongoJsonSchema schema = MongoJsonSchemaCreator.create(mongoOperations.getConverter())
.createSchemaFor(Person.class);

template.createCollection(Person.class, CollectionOptions.empty().schema(schema));
{
‘type’ : ‘object’,
‘required’ : [‘age’],
‘properties’ : {
‘firstname’ : { ‘type’ : ‘string’ },
‘age’ : { ‘bsonType’ : ‘int’ }
‘species’ : {
‘type’ : ‘string’,
‘enum’ : [‘HUMAN’, ‘WOOKIE’, ‘UNKNOWN’]
}
‘address’ : {
‘type’ : ‘object’
‘properties’ : {
‘postCode’ : { ‘type’: ‘string’ }
}
},
‘theForce’ : { ‘type’ : ‘javascript’}
}
}
简单对象属性被视为常规属性。

原始类型被认为是必需的属性

枚举仅限于可能的值。

对象类型属性被检查并表示为嵌套文档。

StringCode由转换器转换为的类型属性。

@Transient 生成模式时省略属性。

_id使用可以转换为ObjectIdlike类型的属性将String被映射到,{ type : ‘object’ } 除非通过@MongoId注释有更具体的信息可用。

Spring认证中国教育管理中心-Spring Data MongoDB教程五
查询匹配 JSON Schema 的集合
您可以使用架构来查询与 JSON 架构定义的给定结构匹配的文档的任何集合,如以下示例所示:

示例 88. 查询匹配 a 的文档 $jsonSchema

MongoJsonSchema schema = MongoJsonSchema.builder().required(“firstname”, “lastname”).build();

template.find(query(matchingDocumentStructure(schema)), Person.class);
加密字段
MongoDB 4.2字段级加密允许直接加密单个属性。

如下例所示,在设置 JSON 架构时,可以将属性包装在加密属性中。

示例 89. 通过 Json Schema 的客户端字段级加密

MongoJsonSchema schema = MongoJsonSchema.builder()
.properties(
encrypted(string(“ssn”))
.algorithm(“AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic”)
.keyId("*key0_id")
).build();
可以利用@Encrypted注释,而不是手动定义加密字段,如下面的代码片段所示。

示例 90. 通过 Json Schema 的客户端字段级加密

@Document
@Encrypted(keyId = “xKVup8B1Q+CkHaVRx+qa+g==”, algorithm = “AEAD_AES_256_CBC_HMAC_SHA_512-Random”)
static class Patient {

@Id String id;
String name;

[@Encrypted](/user/Encrypted) 
String bloodType;

[@Encrypted](/user/Encrypted)(algorithm = "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic") 
Integer ssn;

}
将为 设置的默认加密设置encryptMetadata。

使用默认加密设置的加密字段。

覆盖默认加密算法的加密字段。

@EncryptedAnnoation支持解决通过规划环境地政司表达式keyIds。为此,MappingContext需要并且必须提供额外的环境元数据(通过)。

@Document
@Encrypted(keyId = “#{mongocrypt.keyId(#target)}”)
static class Patient {

@Id String id;
String name;

[@Encrypted](/user/Encrypted)(algorithm = "AEAD_AES_256_CBC_HMAC_SHA_512-Random")
String bloodType;

[@Encrypted](/user/Encrypted)(algorithm = "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic")
Integer ssn;

}

MongoJsonSchemaCreator schemaCreator = MongoJsonSchemaCreator.create(mappingContext);
MongoJsonSchema patientSchema = schemaCreator
.filter(MongoJsonSchemaCreator.encryptedOnly())
.createSchemaFor(Patient.class);
该mongocrypt.keyId函数是通过 定义的
EvaluationContextExtension,如下面的代码片段所示。提供自定义扩展提供了最灵活的计算 keyId 的方式。

public class EncryptionExtension implements EvaluationContextExtension {

@Override
public String getExtensionId() {
    return "mongocrypt";
}

@Override
public Map&lt;String, Function&gt; getFunctions() {
    return Collections.singletonMap("keyId", new Function(getMethod("computeKeyId", String.class), this));
}

public String computeKeyId(String target) {
    // ... lookup via target element name
}

}
要将派生加密设置与
AutoEncryptionSettingsSpring Boot 应用程序结合使用,请使用MongoClientSettingsBuilderCustomizer.

@Bean
MongoClientSettingsBuilderCustomizer customizer(MappingContext mappingContext) {
return (builder) -> {

    // ... keyVaultCollection, kmsProvider, ...

    MongoJsonSchemaCreator schemaCreator = MongoJsonSchemaCreator.create(mappingContext);
    MongoJsonSchema patientSchema = schemaCreator
        .filter(MongoJsonSchemaCreator.encryptedOnly())
        .createSchemaFor(Patient.class);

    AutoEncryptionSettings autoEncryptionSettings = AutoEncryptionSettings.builder()
        .keyVaultNamespace(keyVaultCollection)
        .kmsProviders(kmsProviders)
        .extraOptions(extraOpts)
        .schemaMap(Collections.singletonMap("db.patient", patientSchema.schemaDocument().toBsonDocument()))
        .build();

    builder.autoEncryptionSettings(autoEncryptionSettings);
};

}
确保将驱动程序设置
com.mongodb.AutoEncryptionSettings为使用客户端加密。MongoDB 不支持对所有字段类型进行加密。特定数据类型需要确定性加密以保留相等比较功能。

1 回复

文章内容不错,提个建议:可以适当用一些标题和加粗来分隔开不同段落

回到顶部