Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Query builder index usage optimisations #9

Merged
merged 3 commits into from
Mar 19, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions Sources/FluentMongo/Document+Nested.swift
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,40 @@ public extension Document {
}
}
}

extension Document {

func byRemovingKeysPrefix(_ prefix: String) -> Document {

func removeKeysPrefix(_ document: Document) -> Document {

func ensureNoRootNameSpace(_ value: String) -> String {
let components = value.components(separatedBy: ".")
if components.first == prefix {
return components.dropFirst().joined(separator: ".")
} else {
return value
}
}

var mutableFilter = Document()

for item in document {
switch document[item.key] {
case .some(let value as Document):
mutableFilter[ensureNoRootNameSpace(item.key)] = removeKeysPrefix(value)
case .some(let value as [Document]):
mutableFilter[ensureNoRootNameSpace(item.key)] = value.map { removeKeysPrefix($0) }
case .some(let value):
mutableFilter[ensureNoRootNameSpace(item.key)] = value
case .none:
mutableFilter[ensureNoRootNameSpace(item.key)] = nil
}
}

return mutableFilter
}

return removeKeysPrefix(self)
}
}
34 changes: 21 additions & 13 deletions Sources/FluentMongo/FluentMongoQuery.swift
Original file line number Diff line number Diff line change
Expand Up @@ -67,14 +67,14 @@ public struct FluentMongoQuery {
continue
}

projection[field.pathWithNamespace.joined(separator: ".")] = true
projection[(field.entity == self.collection ? field.path : field.pathWithNamespace).joined(separator: ".")] = true
}

guard !projection.isEmpty else {
return nil
}

projection[self.collection + "._id"] = true
projection["_id"] = true

return projection
}
Expand All @@ -88,18 +88,19 @@ public struct FluentMongoQuery {
continue
}
// It is not possible to use dots when specifying an id field for $group
id[field.pathWithNamespace.joined(separator: ":")] = "$" + field.pathWithNamespace.joined(separator: ".")
let path = (field.entity == self.collection ? field.path : field.pathWithNamespace)
id[field.pathWithNamespace.joined(separator: ":")] = "$" + path.joined(separator: ".")
}

if id.isEmpty {
id[self.collection + ":_id"] = "$" + self.collection + "._id"
id[self.collection + ":_id"] = "$_id"
}

group["_id"] = id
group["doc"] = ["$first": "$" + self.collection] as Document
group["doc"] = ["$first": "$$ROOT"] as Document

stages.append(["$group": group])
stages.append(["$project": [self.collection: "$doc"] as Document])
stages.append(["$replaceRoot": ["newRoot": "$doc"] as Document])

return stages
}
Expand All @@ -122,7 +123,8 @@ public struct FluentMongoQuery {
continue
}
// It seems that fluent only support one aggregated field
group[FluentMongoQuery.defaultAggregateField] = [accumulator.value: "$" + field.pathWithNamespace.joined(separator: ".")] as Document
let path = (field.entity == self.collection ? field.path : field.pathWithNamespace).joined(separator: ".")
group[FluentMongoQuery.defaultAggregateField] = [accumulator.value: "$" + path] as Document
break
}

Expand All @@ -136,9 +138,6 @@ public struct FluentMongoQuery {
func aggregationPipeline() -> [Document] {
var pipeline = [Document]()

// Namespace root document
pipeline.append(["$project": [self.collection: "$$ROOT"] as Document])

// Joins
if !self.joins.isEmpty {
pipeline.append(contentsOf: self.joins)
Expand Down Expand Up @@ -177,9 +176,18 @@ public struct FluentMongoQuery {
// Aggregates
if let aggregates = self.aggregates() {
pipeline.append(contentsOf: aggregates)
} else {
// Remove namespace
pipeline.append(["$replaceRoot": ["newRoot": "$" + self.collection] as Document])
}

// Remove joined collections from the output
if !self.joins.isEmpty {
var projection = Document()
for join in self.joins {
guard let field = join["$lookup", "as"] as? String else {
continue
}
projection[field] = false
}
pipeline.append(["$project": projection])
}

return pipeline
Expand Down
7 changes: 5 additions & 2 deletions Sources/FluentMongo/FluentMongoQueryFilter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,14 @@ extension Database where Self: QuerySupporting, Self.Query == FluentMongoQuery,
}

public static func queryFilterApply(_ filter: QueryFilter, to query: inout Query) {

let filterByRemovingRootNamespace = filter.byRemovingKeysPrefix(query.collection)

switch query.filter {
case .some(let document):
query.filter = [query.defaultFilterRelation.rawValue: [document, filter]]
query.filter = [query.defaultFilterRelation.rawValue: [document, filterByRemovingRootNamespace]]
case .none:
query.filter = filter
query.filter = filterByRemovingRootNamespace
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion Sources/FluentMongo/FluentMongoQueryJoin.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ extension Database where Self: JoinSupporting, Self.QueryJoin == FluentMongoQuer
let lookup: Document = [
"$lookup": [
"from": collection,
"localField": base.pathWithNamespace.joined(separator: "."),
"localField": base.path.joined(separator: "."),
"foreignField": joined.path.joined(separator: "."),
"as": collection
] as Document
Expand Down
2 changes: 1 addition & 1 deletion Sources/FluentMongo/FluentMongoQuerySort.swift
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ extension Database where Self: QuerySupporting, Self.Query == FluentMongoQuery,
for field in sort {
document[field.key] = field.value
}
query.sort = document
query.sort = document.byRemovingKeysPrefix(query.collection)
}
}

Expand Down