1
|
|
|
"""networkx-query public interace definition.""" |
2
|
|
|
from typing import Any, Dict, Iterable, Tuple |
3
|
|
|
|
4
|
|
|
from networkx import Graph |
5
|
|
|
|
6
|
|
|
from .parser import prepare_query |
7
|
|
|
from .utils import get_first_item, get_two_first_items |
8
|
|
|
|
9
|
|
|
__all__ = ['search_nodes', 'search_edges'] |
10
|
|
|
|
11
|
|
|
|
12
|
|
|
def search_nodes(graph: Graph, query: Dict) -> Iterable[Any]: |
13
|
|
|
"""Search nodes in specified graph which match query. |
14
|
|
|
|
15
|
|
|
Arguments: |
16
|
|
|
graph (Graph): networkx graph instance |
17
|
|
|
query (Dict): query expression |
18
|
|
|
|
19
|
|
|
Returns: |
20
|
|
|
(Iterable[Any]): results as an iterable of node identifier. |
21
|
|
|
|
22
|
|
|
Exceptions: |
23
|
|
|
(ParserException): if a parse error occurs |
24
|
|
|
|
25
|
|
|
""" |
26
|
|
|
_predicate = prepare_query(query) |
27
|
|
|
return map(get_first_item, filter(lambda node: _predicate(node[1]), graph.nodes(data=True))) |
28
|
|
|
|
29
|
|
|
|
30
|
|
|
def search_edges(graph: Graph, query: Dict) -> Iterable[Tuple]: |
31
|
|
|
"""Search edges in specified graph which match query. |
32
|
|
|
|
33
|
|
|
Arguments: |
34
|
|
|
graph (Graph): networkx graph instance |
35
|
|
|
query (Dict): query expression |
36
|
|
|
|
37
|
|
|
Returns: |
38
|
|
|
(Iterable[Tuple]): results as an iterable of edge identifier (tuple). |
39
|
|
|
|
40
|
|
|
Exceptions: |
41
|
|
|
(ParserException): if a parse error occurs |
42
|
|
|
|
43
|
|
|
""" |
44
|
|
|
_predicate = prepare_query(query) |
45
|
|
|
return map(get_two_first_items, filter(lambda edge: _predicate(edge[2]), graph.edges(data=True))) |
46
|
|
|
|