generated from amosproj/amos202Xss0Y-projname
-
Notifications
You must be signed in to change notification settings - Fork 0
/
filter.service.ts
247 lines (222 loc) · 8.21 KB
/
filter.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
import { Injectable } from '@nestjs/common';
import { Neo4jService } from 'nest-neo4j/dist';
import { EdgeDescriptor, NodeDescriptor } from '../shared/entities';
import { consolidateQueryResult, allocateQueryParamName } from '../utils';
import { FilterCondition, FilterQuery, QueryResult } from '../shared/queries';
import FilterConditionBuilder from './FilterConditionBuilder';
import { FilterServiceBase } from './filter.service.base';
import {
EdgeTypeFilterModel,
FilterModelEntry,
NodeTypeFilterModel,
} from '../shared/filter';
import {
neo4jReturnEdgeDescriptor,
neo4jReturnNodeDescriptor,
} from '../config/commonFunctions';
/**
* The default implementation of the filter service for the neo4j database.
*/
@Injectable()
export class FilterService implements FilterServiceBase {
constructor(private readonly neo4jService: Neo4jService) {}
/**
* @inheritdoc
*/
async query(query?: FilterQuery): Promise<QueryResult> {
// Extract the necessary parameters from the query object split for
// nodes and edges as we process them separately.
const nodeFilter = query?.filters?.nodes;
const nodeLimit = query?.limits?.nodes;
// Request the nodes from the database, or use an empty array, if the
// limit is set to zero, as the database interprets a limit of zero
// as unlimited.
const nodes =
nodeLimit === 0 ? [] : await this.getNodes(nodeFilter, nodeLimit);
const edgeFilter = query?.filters?.edges;
const edgeLimit = query?.limits?.edges;
// Request the edges from the database, or use an empty array, if the
// limit is set to zero, as the database interprets a limit of zero
// as unlimited.
const edges =
edgeLimit === 0 ? [] : await this.getEdges(edgeFilter, edgeLimit);
// Build our query result.
const queryResult = { nodes, edges };
// Post process the query result to dedupe entities and consolidate
// references nodes.
return consolidateQueryResult(
queryResult,
query?.includeSubsidiary ?? false
);
}
/**
* Requests all nodes that match the specified filter condition within the
* specified limits.
* @param filter The filter condition or `undefined` to query all nodes.
* @param limit The maximum number of nodes to return or 'undefined' if no limit is set.
*/
private async getNodes(
filter?: FilterCondition,
limit?: number
): Promise<NodeDescriptor[]> {
// First build the query-condition, that is the "WHERE" clause of the cypher
// query with the help of the FilterConditionBuilder type.
// The 'condition' variable contains our condition, or null if no condition is
// specified (query-all), the 'queryParams' variable contains the database
// query parameters (key-value pairs) that we can extend and pass to the
// database.
const {
condition,
queryParams,
} = FilterConditionBuilder.buildFilterCondition('node', 'n', filter);
// Now build the cypher query in the form
// MATCH (n)
// WHERE { condition }
// RETURN ID(n) as id
// LIMIT toInteger({ limit })
let query = 'MATCH (n)';
// Only add the WHERE clause and the condition if there is a condition set.
if (condition !== null) {
query = `${query} WHERE ${condition}`;
}
query = `${query} RETURN ${neo4jReturnNodeDescriptor('n')}`;
// Only add a LIMIT clause if a limit is specified.
if (limit !== undefined) {
const limitParamKey = allocateQueryParamName(queryParams, 'limit');
// toInteger required, since apparently it converts int to double.
query = `${query} LIMIT toInteger($${limitParamKey})`;
queryParams[limitParamKey] = limit;
}
// Now execute the query and transform the query result to the type of
// result we can further process.
const result = await this.neo4jService.read(query, queryParams);
return result.records.map((x) => x.toObject() as NodeDescriptor);
}
/**
* Requests all edges that match the specified filter condition within the
* specified limits.
* @param filter The filter condition or `undefined` to query all edges.
* @param limit The maximum number of edges to return or 'undefined' if no limit is set.
*/
private async getEdges(
filter?: FilterCondition,
limit?: number
): Promise<EdgeDescriptor[]> {
// First build the query-condition, that is the "WHERE" clause of the cypher
// query with the help of the FilterConditionBuilder type.
// The 'condition' variable contains our condition, or null if no condition is
// specified (query-all), the 'queryParams' variable contains the database
// query parameters (key-value pairs) that we can extend and pass to the
// database.
const {
condition,
queryParams,
} = FilterConditionBuilder.buildFilterCondition('edge', 'e', filter);
// Now build the cypher query in the form
// MATCH MATCH (from)-[e]->(to)
// WHERE { condition }
// RETURN RETURN ID(e) as id, ID(from) as from, ID(to) as to
// LIMIT toInteger({ limit })
let query = 'MATCH (from)-[e]->(to)';
// Only add the WHERE clause and the condition if there is a condition set.
if (condition !== null) {
query = `${query} WHERE ${condition}`;
}
query = `${query} RETURN ${neo4jReturnEdgeDescriptor('e', 'from', 'to')}`;
// Only add a LIMIT clause if a limit is specified.
if (limit !== undefined) {
const limitParamKey = allocateQueryParamName(queryParams, 'limit');
// toInteger required, since apparently it converts int to double.
query = `${query} LIMIT toInteger($${limitParamKey})`;
queryParams[limitParamKey] = limit;
}
// Now execute the query and transform the query result to the type of
// result we can further process.
const result = await this.neo4jService.read(query, queryParams);
return result.records.map((x) => x.toObject() as EdgeDescriptor);
}
/**
* @inheritdoc
*/
public async getNodeTypeFilterModel(
type: string
): Promise<NodeTypeFilterModel> {
// This basically looks up the values that are present in the database for each property of all
// entities of the specified type in a distinct way.
// Example:
// Say, the db contains for the specified type these entries (where name and date are properties):
// | id | name | date |
// | 1 | abc | 20/1/1 |
// | 2 | abc | 20/1/1 |
// | 3 | abc | 22/1/1 |
// | 5 | def | 21/2/3 |
// The result would look like:
// name: [abc, def]
// date: [20/1/1, 22/1/1, 21/2/3]
const result = await this.neo4jService.read(
`
MATCH (n)
WHERE $nodeType in labels(n)
UNWIND keys(n) as m_keys
WITH collect(distinct m_keys) as c_keys
UNWIND c_keys AS key
CALL {
WITH key
MATCH (m)
RETURN collect(distinct m[key]) as values
}
RETURN key, values
`,
{ nodeType: type }
);
const properties = result.records.map(
(x) => x.toObject() as FilterModelEntry
);
return {
name: type,
properties,
};
}
/**
* @inheritdoc
*/
public async getEdgeTypeFilterModel(
type: string
): Promise<EdgeTypeFilterModel> {
// This basically looks up the values that are present in the database for each property of all
// entities of the specified type in a distinct way.
// Example:
// Say, the db contains for the specified type these entries (where name and date are properties):
// | id | name | date |
// | 1 | abc | 20/1/1 |
// | 2 | abc | 20/1/1 |
// | 3 | abc | 22/1/1 |
// | 5 | def | 21/2/3 |
// The result would look like:
// name: [abc, def]
// date: [20/1/1, 22/1/1, 21/2/3]
const result = await this.neo4jService.read(
`
MATCH ()-[n]->()
WHERE $edgeType = type(n)
UNWIND keys(n) as m_keys
WITH collect(distinct m_keys) as c_keys
UNWIND c_keys AS key
CALL {
WITH key
MATCH ()-[m]->()
RETURN collect(distinct m[key]) as values
}
RETURN key, values
`,
{ edgeType: type }
);
const properties = result.records.map(
(x) => x.toObject() as FilterModelEntry
);
return {
name: type,
properties,
};
}
}