knowrob  2.1.0
A Knowledge Base System for Cognition-enabled Robots
knowrob::MongoKnowledgeGraph Class Reference

#include <MongoKnowledgeGraph.h>

Inheritance diagram for knowrob::MongoKnowledgeGraph:
Collaboration diagram for knowrob::MongoKnowledgeGraph:

Classes

class  ConnectionRAII
 

Public Member Functions

 MongoKnowledgeGraph ()
 
 ~MongoKnowledgeGraph () override=default
 
bool initializeBackend (std::string_view db_uri, std::string_view db_name="knowrob", std::string_view collectionName="triples")
 
bool initializeBackend (const PropertyTree &config) override
 
const std::string & dbName () const
 
const std::string & dbURI () const
 
bool isReadOnly () const
 
auto tripleCollection ()
 
void drop ()
 
mongo::BindingsCursorPtr lookup (const TriplePattern &query)
 
mongo::BindingsCursorPtr lookup (const GraphTerm &query)
 
bool insertOne (const Triple &triple) override
 
bool insertAll (const TripleContainerPtr &triples) override
 
bool removeOne (const Triple &triple) override
 
bool removeAll (const TripleContainerPtr &triples) override
 
bool removeAllWithOrigin (std::string_view origin) override
 
bool isPersistent () const override
 
void foreach (const TripleVisitor &callback) const override
 
void batch (const TripleHandler &callback) const override
 
void batchOrigin (std::string_view origin, const TripleHandler &callback) override
 
void match (const TriplePattern &query, const TripleVisitor &visitor) override
 
void query (const GraphQueryPtr &query, const BindingsHandler &callback) override
 
void count (const ResourceCounter &callback) const override
 
 MongoKnowledgeGraph ()
 
 ~MongoKnowledgeGraph () override=default
 
bool initializeBackend (std::string_view db_uri, std::string_view db_name="knowrob", std::string_view collectionName="triples")
 
bool initializeBackend (const PropertyTree &config) override
 
const std::string & dbName () const
 
const std::string & dbURI () const
 
bool isReadOnly () const
 
auto tripleCollection ()
 
void drop ()
 
mongo::BindingsCursorPtr lookup (const TriplePattern &query)
 
mongo::BindingsCursorPtr lookup (const GraphTerm &query)
 
bool insertOne (const Triple &triple) override
 
bool insertAll (const TripleContainerPtr &triples) override
 
bool removeOne (const Triple &triple) override
 
bool removeAll (const TripleContainerPtr &triples) override
 
bool removeAllWithOrigin (std::string_view origin) override
 
bool isPersistent () const override
 
void foreach (const TripleVisitor &callback) const override
 
void batch (const TripleHandler &callback) const override
 
void batchOrigin (std::string_view origin, const TripleHandler &callback) override
 
void match (const TriplePattern &query, const TripleVisitor &visitor) override
 
void query (const GraphQueryPtr &query, const BindingsHandler &callback) override
 
void count (const ResourceCounter &callback) const override
 
- Public Member Functions inherited from knowrob::QueryableStorage
 QueryableStorage (StorageFeatures features=StorageFeature::NothingSpecial)
 
 ~QueryableStorage () override=default
 
virtual bool contains (const Triple &triple)
 
std::vector< VersionedOriginPtrgetOrigins ()
 
std::optional< std::string > getVersionOfOrigin (std::string_view origin)
 
void setVersionOfOrigin (std::string_view origin, std::string_view version)
 
void dropSessionOrigins ()
 
GraphQueryExpansionPtr expand (const GraphQueryPtr &q)
 
 QueryableStorage (StorageFeatures features=StorageFeature::NothingSpecial)
 
 ~QueryableStorage () override=default
 
virtual bool contains (const Triple &triple)
 
std::vector< VersionedOriginPtrgetOrigins ()
 
std::optional< std::string > getVersionOfOrigin (std::string_view origin)
 
void setVersionOfOrigin (std::string_view origin, std::string_view version)
 
void dropSessionOrigins ()
 
GraphQueryExpansionPtr expand (const GraphQueryPtr &q)
 
- Public Member Functions inherited from knowrob::Storage
 Storage (StorageFeatures features=StorageFeature::NothingSpecial)
 
virtual ~Storage ()=default
 
PluginLanguage storageLanguage () const
 
const auto & vocabulary () const
 
void setVocabulary (std::shared_ptr< Vocabulary > vocabulary)
 
bool supports (StorageFeature feature) const
 
std::optional< std::string > getVersionOfOrigin (std::string_view origin) const
 
void setVersionOfOrigin (std::string_view origin, std::optional< std::string_view > version)
 
 Storage (StorageFeatures features=StorageFeature::NothingSpecial)
 
virtual ~Storage ()=default
 
PluginLanguage storageLanguage () const
 
const auto & vocabulary () const
 
void setVocabulary (std::shared_ptr< Vocabulary > vocabulary)
 
bool supports (StorageFeature feature) const
 
std::optional< std::string > getVersionOfOrigin (std::string_view origin) const
 
void setVersionOfOrigin (std::string_view origin, std::optional< std::string_view > version)
 
- Public Member Functions inherited from knowrob::DataSourceHandler
 DataSourceHandler ()=default
 
virtual ~DataSourceHandler ()=default
 
void addDataHandler (const std::string &format, const DataSourceLoader &fn)
 
bool loadDataSource (const DataSourcePtr &dataSource)
 
bool hasDataHandler (const DataSourcePtr &dataSource) const
 
 DataSourceHandler ()=default
 
virtual ~DataSourceHandler ()=default
 
void addDataHandler (const std::string &format, const DataSourceLoader &fn)
 
bool loadDataSource (const DataSourcePtr &dataSource)
 
bool hasDataHandler (const DataSourcePtr &dataSource) const
 

Static Public Attributes

static const std::string DB_URI_DEFAULT = "mongodb://localhost:27017"
 
static const std::string DB_NAME_KNOWROB = "knowrob"
 
static const std::string DB_NAME_TESTS = "knowrob_test"
 
static const std::string COLL_NAME_TRIPLES = "triples"
 
static const std::string COLL_NAME_TESTS = "triples_test"
 
- Static Public Attributes inherited from knowrob::QueryableStorage
static AtomPtr versionProperty = IRIAtom::Tabled("http://knowrob.org/kb/knowrob.owl#hasVersionOfOrigin")
 

Protected Member Functions

void initializeMongo (const std::shared_ptr< mongo::Collection > &tripleCollection)
 
bool dropOrigin (std::string_view origin)
 
mongo::TripleStore acquireStore () const
 
void releaseStore (mongo::TripleStore &store) const
 
void initializeMongo (const std::shared_ptr< mongo::Collection > &tripleCollection)
 
bool dropOrigin (std::string_view origin)
 
mongo::TripleStore acquireStore () const
 
void releaseStore (mongo::TripleStore &store) const
 
- Protected Member Functions inherited from knowrob::Storage
void enableFeature (StorageFeature feature)
 
void setStorageLanguage (PluginLanguage storageLanguage)
 
void enableFeature (StorageFeature feature)
 
void setStorageLanguage (PluginLanguage storageLanguage)
 
- Protected Member Functions inherited from knowrob::DataSourceHandler
virtual bool loadDataSourceWithUnknownFormat (const DataSourcePtr &)
 
virtual bool loadDataSourceWithUnknownFormat (const DataSourcePtr &)
 

Static Protected Member Functions

static void iterate (mongo::TripleCursor &cursor, const TripleVisitor &visitor)
 
static std::shared_ptr< mongo::Collectionconnect (const boost::property_tree::ptree &config)
 
static std::shared_ptr< mongo::Collectionconnect (std::string_view uri, std::string_view db, std::string_view collection)
 
static std::string getDBName (const boost::property_tree::ptree &config)
 
static std::string getCollectionName (const boost::property_tree::ptree &config)
 
static std::string getURI (const boost::property_tree::ptree &config)
 
static void iterate (mongo::TripleCursor &cursor, const TripleVisitor &visitor)
 
static std::shared_ptr< mongo::Collectionconnect (const boost::property_tree::ptree &config)
 
static std::shared_ptr< mongo::Collectionconnect (std::string_view uri, std::string_view db, std::string_view collection)
 
static std::string getDBName (const boost::property_tree::ptree &config)
 
static std::string getCollectionName (const boost::property_tree::ptree &config)
 
static std::string getURI (const boost::property_tree::ptree &config)
 

Protected Attributes

std::shared_ptr< mongo::CollectiontripleCollection_
 
std::shared_ptr< mongo::CollectiononeCollection_
 
std::shared_ptr< mongo::MongoTaxonomytaxonomy_
 
bool isReadOnly_
 
std::mutex storeMutex_
 
std::list< mongo::TripleStoreconnections_
 
- Protected Attributes inherited from knowrob::Storage
std::map< std::string, std::string > originVersions_
 
std::shared_ptr< Vocabularyvocabulary_
 
StorageFeatures features_
 
PluginLanguage storageLanguage_
 
- Protected Attributes inherited from knowrob::DataSourceHandler
std::map< std::string, DataSourceLoaderdataSourceHandler_
 

Friends

class ConnectionRAII
 

Additional Inherited Members

- Static Public Member Functions inherited from knowrob::QueryableStorage
static std::shared_ptr< AnswerYesyes (const GraphPathQueryPtr &original, const GraphQueryExpansionPtr &expansion, const BindingsPtr &bindings)
 
static std::shared_ptr< AnswerNono (const GraphPathQueryPtr &q)
 
static std::shared_ptr< AnswerYesyes (const GraphPathQueryPtr &original, const GraphQueryExpansionPtr &expansion, const BindingsPtr &bindings)
 
static std::shared_ptr< AnswerNono (const GraphPathQueryPtr &q)
 

Detailed Description

A knowledge graph implemented with MongoDB.

Definition at line 26 of file MongoKnowledgeGraph.h.

Constructor & Destructor Documentation

◆ MongoKnowledgeGraph() [1/2]

MongoKnowledgeGraph::MongoKnowledgeGraph ( )

Definition at line 58 of file MongoKnowledgeGraph.cpp.

59  : QueryableStorage(mongoBackendFeatures()),
60  isReadOnly_(false) {
61 }
QueryableStorage(StorageFeatures features=StorageFeature::NothingSpecial)

◆ ~MongoKnowledgeGraph() [1/2]

knowrob::MongoKnowledgeGraph::~MongoKnowledgeGraph ( )
overridedefault

◆ MongoKnowledgeGraph() [2/2]

knowrob::MongoKnowledgeGraph::MongoKnowledgeGraph ( )

◆ ~MongoKnowledgeGraph() [2/2]

knowrob::MongoKnowledgeGraph::~MongoKnowledgeGraph ( )
overridedefault

Member Function Documentation

◆ acquireStore() [1/2]

mongo::TripleStore MongoKnowledgeGraph::acquireStore ( ) const
protected

Definition at line 70 of file MongoKnowledgeGraph.cpp.

70  {
71  // Note: We cannot use a Collection object in different threads, so instead we manage
72  // a list of active connections and hand them out to threads that need them.
73  // If no connection is available, a new one is created on the fly.
74  std::lock_guard<std::mutex> lock(storeMutex_);
75  if (connections_.empty()) {
76  auto tripleCollection = std::make_shared<Collection>(*tripleCollection_);
77  auto oneCollection = std::make_shared<Collection>(
78  tripleCollection->connection(),
79  tripleCollection->dbName().c_str(),
81  return {tripleCollection, oneCollection, vocabulary_};
82  } else {
83  auto store = connections_.front();
84  connections_.pop_front();
85  return store;
86  }
87 }
#define MONGO_KG_ONE_COLLECTION
std::shared_ptr< mongo::Collection > tripleCollection_
std::list< mongo::TripleStore > connections_
std::shared_ptr< Vocabulary > vocabulary_
Definition: Storage.h:143

◆ acquireStore() [2/2]

mongo::TripleStore knowrob::MongoKnowledgeGraph::acquireStore ( ) const
protected

◆ batch() [1/2]

void MongoKnowledgeGraph::batch ( const TripleHandler callback) const
overridevirtual

Iterate over all triples in the model.

Parameters
callbackthe callback to handle the triples.
Returns
true if the iteration was successful.

Implements knowrob::QueryableStorage.

Definition at line 409 of file MongoKnowledgeGraph.cpp.

409  {
410  ConnectionRAII scoped(this);
411  batch_(scoped.mongo.tripleCollection, callback, nullptr);
412 }

◆ batch() [2/2]

void knowrob::MongoKnowledgeGraph::batch ( const TripleHandler callback) const
overridevirtual

Iterate over all triples in the model.

Parameters
callbackthe callback to handle the triples.
Returns
true if the iteration was successful.

Implements knowrob::QueryableStorage.

◆ batchOrigin() [1/2]

void MongoKnowledgeGraph::batchOrigin ( std::string_view  origin,
const TripleHandler callback 
)
overridevirtual

Iterate over all triples in the model that have a given origin.

Parameters
originthe origin of the triples.
callbackthe callback to handle the triples.
Returns
true if the iteration was successful.

Implements knowrob::QueryableStorage.

Definition at line 414 of file MongoKnowledgeGraph.cpp.

414  {
415  ConnectionRAII scoped(this);
416  bson_t filterDoc;
417  BSON_APPEND_UTF8(&filterDoc, "graph", origin.data());
418  batch_(scoped.mongo.tripleCollection, callback, &filterDoc);
419 }

◆ batchOrigin() [2/2]

void knowrob::MongoKnowledgeGraph::batchOrigin ( std::string_view  origin,
const TripleHandler callback 
)
overridevirtual

Iterate over all triples in the model that have a given origin.

Parameters
originthe origin of the triples.
callbackthe callback to handle the triples.
Returns
true if the iteration was successful.

Implements knowrob::QueryableStorage.

◆ connect() [1/4]

std::shared_ptr< Collection > MongoKnowledgeGraph::connect ( const boost::property_tree::ptree &  config)
staticprotected

Definition at line 191 of file MongoKnowledgeGraph.cpp.

191  {
192  return connect(getURI(config), getDBName(config), getCollectionName(config));
193 }
static std::shared_ptr< mongo::Collection > connect(const boost::property_tree::ptree &config)
static std::string getURI(const boost::property_tree::ptree &config)
static std::string getCollectionName(const boost::property_tree::ptree &config)
static std::string getDBName(const boost::property_tree::ptree &config)

◆ connect() [2/4]

static std::shared_ptr<mongo::Collection> knowrob::MongoKnowledgeGraph::connect ( const boost::property_tree::ptree &  config)
staticprotected

◆ connect() [3/4]

std::shared_ptr< Collection > MongoKnowledgeGraph::connect ( std::string_view  uri,
std::string_view  db,
std::string_view  collection 
)
staticprotected

Definition at line 178 of file MongoKnowledgeGraph.cpp.

181  {
182  auto coll = MongoInterface::get().connect(db_uri.data(), db_name.data(), collectionName.data());
183  if (coll) {
184  KB_INFO("[mongodb] connected to {} ({}.{}).", db_uri, db_name, collectionName);
185  } else {
186  KB_ERROR("[mongodb] failed to connect to {} ({}.{}).", db_uri, db_name, collectionName);
187  }
188  return coll;
189 }
#define KB_INFO
Definition: Logger.h:26
#define KB_ERROR
Definition: Logger.h:28

◆ connect() [4/4]

static std::shared_ptr<mongo::Collection> knowrob::MongoKnowledgeGraph::connect ( std::string_view  uri,
std::string_view  db,
std::string_view  collection 
)
staticprotected

◆ count() [1/2]

void MongoKnowledgeGraph::count ( const ResourceCounter callback) const
overridevirtual
Parameters
callbacka function that is called for each resource and its count.

Implements knowrob::QueryableStorage.

Definition at line 332 of file MongoKnowledgeGraph.cpp.

332  {
333  ConnectionRAII scoped(this);
334  for (auto &filename: {PIPELINE_RELATION_COUNTER, PIPELINE_CLASS_COUNTER}) {
335  const bson_t *result;
336  Cursor cursor(scoped.mongo.tripleCollection);
337  Document document(Pipeline::loadFromJSON(
338  filename, {
339  {"COLLECTION", scoped.mongo.tripleCollection->name()}
340  }));
341  cursor.aggregate(document.bson());
342  while (cursor.next(&result)) {
343  bson_iter_t iter;
344  if (!bson_iter_init(&iter, result)) break;
345  if (!bson_iter_find(&iter, "resource")) break;
346  auto property = bson_iter_utf8(&iter, nullptr);
347  if (!bson_iter_find(&iter, "count")) break;
348  auto count = bson_iter_as_int64(&iter);
349  callback(property, count);
350  }
351  }
352 }
#define PIPELINE_CLASS_COUNTER
#define PIPELINE_RELATION_COUNTER
void count(const ResourceCounter &callback) const override

◆ count() [2/2]

void knowrob::MongoKnowledgeGraph::count ( const ResourceCounter callback) const
overridevirtual
Parameters
callbacka function that is called for each resource and its count.

Implements knowrob::QueryableStorage.

◆ dbName() [1/2]

const std::string& knowrob::MongoKnowledgeGraph::dbName ( ) const
inline
Returns
the name of the database.

Definition at line 55 of file MongoKnowledgeGraph.h.

55 { return tripleCollection_->dbName(); }

◆ dbName() [2/2]

const std::string& knowrob::MongoKnowledgeGraph::dbName ( ) const
inline
Returns
the name of the database.

Definition at line 55 of file MongoKnowledgeGraph.h.

55 { return tripleCollection_->dbName(); }

◆ dbURI() [1/2]

const std::string& knowrob::MongoKnowledgeGraph::dbURI ( ) const
inline
Returns
the URI string used to connect to the database.

Definition at line 60 of file MongoKnowledgeGraph.h.

60 { return tripleCollection_->dbURI(); }

◆ dbURI() [2/2]

const std::string& knowrob::MongoKnowledgeGraph::dbURI ( ) const
inline
Returns
the URI string used to connect to the database.

Definition at line 60 of file MongoKnowledgeGraph.h.

60 { return tripleCollection_->dbURI(); }

◆ drop() [1/2]

void MongoKnowledgeGraph::drop ( )

Delete all statements in the database. Note: ths will also delete all indices which need to be re-created afterwards.

Definition at line 227 of file MongoKnowledgeGraph.cpp.

227  {
228  ConnectionRAII scoped(this);
229  scoped.mongo.tripleCollection->drop();
230  vocabulary_ = std::make_shared<Vocabulary>();
231 }

◆ drop() [2/2]

void knowrob::MongoKnowledgeGraph::drop ( )

Delete all statements in the database. Note: ths will also delete all indices which need to be re-created afterwards.

◆ dropOrigin() [1/2]

bool MongoKnowledgeGraph::dropOrigin ( std::string_view  origin)
protected

Definition at line 320 of file MongoKnowledgeGraph.cpp.

320  {
321  KB_DEBUG("[mongodb] dropping triples with origin \"{}\".", graphName);
322  ConnectionRAII scoped(this);
323  scoped.mongo.tripleCollection->removeAll(Document(
324  BCON_NEW("graph", BCON_UTF8(graphName.data()))));
325  return true;
326 }
#define KB_DEBUG
Definition: Logger.h:25

◆ dropOrigin() [2/2]

bool knowrob::MongoKnowledgeGraph::dropOrigin ( std::string_view  origin)
protected

◆ foreach() [1/2]

void MongoKnowledgeGraph::foreach ( const TripleVisitor visitor) const
overridevirtual

Iterate over all triples in the model.

Parameters
visitorthe callback to handle the triples.
Returns
true if the iteration was successful.

Reimplemented from knowrob::QueryableStorage.

Definition at line 369 of file MongoKnowledgeGraph.cpp.

369  {
370  ConnectionRAII scoped(this);
371  TripleCursor cursor(scoped.mongo.tripleCollection);
372  iterate(cursor, visitor);
373 }
static void iterate(mongo::TripleCursor &cursor, const TripleVisitor &visitor)

◆ foreach() [2/2]

void knowrob::MongoKnowledgeGraph::foreach ( const TripleVisitor visitor) const
overridevirtual

Iterate over all triples in the model.

Parameters
visitorthe callback to handle the triples.
Returns
true if the iteration was successful.

Reimplemented from knowrob::QueryableStorage.

◆ getCollectionName() [1/2]

std::string MongoKnowledgeGraph::getCollectionName ( const boost::property_tree::ptree &  config)
staticprotected

Definition at line 201 of file MongoKnowledgeGraph.cpp.

201  {
202  static std::string defaultCollectionName = MONGO_KG_DEFAULT_COLLECTION;
203  auto o_collection = config.get_optional<std::string>(MONGO_KG_SETTING_COLLECTION);
204  return (o_collection ? o_collection.value() : defaultCollectionName);
205 }
#define MONGO_KG_SETTING_COLLECTION
#define MONGO_KG_DEFAULT_COLLECTION
TermRule & string()
Definition: terms.cpp:63

◆ getCollectionName() [2/2]

static std::string knowrob::MongoKnowledgeGraph::getCollectionName ( const boost::property_tree::ptree &  config)
staticprotected

◆ getDBName() [1/2]

std::string MongoKnowledgeGraph::getDBName ( const boost::property_tree::ptree &  config)
staticprotected

Definition at line 195 of file MongoKnowledgeGraph.cpp.

195  {
196  static std::string defaultDBName = MONGO_KG_DEFAULT_DB;
197  auto o_dbname = config.get_optional<std::string>(MONGO_KG_SETTING_DB);
198  return (o_dbname ? o_dbname.value() : defaultDBName);
199 }
#define MONGO_KG_DEFAULT_DB
#define MONGO_KG_SETTING_DB

◆ getDBName() [2/2]

static std::string knowrob::MongoKnowledgeGraph::getDBName ( const boost::property_tree::ptree &  config)
staticprotected

◆ getURI() [1/2]

std::string MongoKnowledgeGraph::getURI ( const boost::property_tree::ptree &  config)
staticprotected

Definition at line 207 of file MongoKnowledgeGraph.cpp.

207  {
208  auto o_host = config.get_optional<std::string>(MONGO_KG_SETTING_HOST);
209  auto o_port = config.get_optional<std::string>(MONGO_KG_SETTING_PORT);
210  auto o_user = config.get_optional<std::string>(MONGO_KG_SETTING_USER);
211  auto o_password = config.get_optional<std::string>(MONGO_KG_SETTING_PASSWORD);
212  // format URI of the form "mongodb://USER:PW@HOST:PORT"
213  std::stringstream uriStream;
214  uriStream << "mongodb://";
215  if (o_user) {
216  uriStream << o_user.value();
217  if (o_password) uriStream << ':' << o_password.value();
218  uriStream << '@';
219  }
220  uriStream
221  << (o_host ? o_host.value() : MONGO_KG_DEFAULT_HOST)
222  << ':'
223  << (o_port ? o_port.value() : MONGO_KG_DEFAULT_PORT);
224  return uriStream.str();
225 }
#define MONGO_KG_DEFAULT_PORT
#define MONGO_KG_DEFAULT_HOST
#define MONGO_KG_SETTING_USER
#define MONGO_KG_SETTING_PASSWORD
#define MONGO_KG_SETTING_HOST
#define MONGO_KG_SETTING_PORT

◆ getURI() [2/2]

static std::string knowrob::MongoKnowledgeGraph::getURI ( const boost::property_tree::ptree &  config)
staticprotected

◆ initializeBackend() [1/4]

bool MongoKnowledgeGraph::initializeBackend ( const PropertyTree config)
overridevirtual

Initialize this backend from a property tree.

Parameters
configa property tree.
Returns
true on success

Implements knowrob::Storage.

Definition at line 108 of file MongoKnowledgeGraph.cpp.

108  {
109  auto ptree = config.ptree();
110  if (!ptree) {
112  if (tripleCollection) {
115  return true;
116  } else {
117  return false;
118  }
119  }
120  initializeMongo(connect(*ptree));
121 
122  // set isReadOnly_ flag
123  auto o_readOnly = ptree->get_optional<bool>(MONGO_KG_SETTING_READ_ONLY);
124  if (o_readOnly.has_value()) {
125  isReadOnly_ = o_readOnly.value();
126  }
127  if (!isReadOnly_) {
129  }
130 
131  // Auto-drop some named graphs
132  auto o_drop = ptree->get_child_optional(MONGO_KG_SETTING_DROP);
133  if (o_drop.has_value()) {
134  if (std::string_view("*") == std::string_view(o_drop.value().data())) {
135  drop();
136  tripleCollection_->createTripleIndex();
137  } else {
138  BOOST_FOREACH(const auto &v, o_drop.value()) {
139  removeAllWithOrigin(v.second.data());
140  }
141  }
142  }
143 
144  return true;
145 }
#define MONGO_KG_SETTING_DROP
#define MONGO_KG_SETTING_READ_ONLY
void initializeMongo(const std::shared_ptr< mongo::Collection > &tripleCollection)
static const std::string DB_NAME_KNOWROB
static const std::string COLL_NAME_TESTS
static const std::string DB_URI_DEFAULT
bool removeAllWithOrigin(std::string_view origin) override
auto ptree() const
Definition: PropertyTree.h:88

◆ initializeBackend() [2/4]

bool knowrob::MongoKnowledgeGraph::initializeBackend ( const PropertyTree config)
overridevirtual

Initialize this backend from a property tree.

Parameters
configa property tree.
Returns
true on success

Implements knowrob::Storage.

◆ initializeBackend() [3/4]

bool MongoKnowledgeGraph::initializeBackend ( std::string_view  db_uri,
std::string_view  db_name = "knowrob",
std::string_view  collectionName = "triples" 
)

Initialize the knowledge graph with a MongoDB URI.

Parameters
db_urithe URI string used to connect to the database.
db_namethe name of the database.
collectionNamethe name of the collection for triples.
Returns
true on success

Definition at line 96 of file MongoKnowledgeGraph.cpp.

97  {
98  auto tripleCollection = connect(db_uri, db_name, collectionName);
99  if (tripleCollection) {
102  return true;
103  } else {
104  return false;
105  }
106 }

◆ initializeBackend() [4/4]

bool knowrob::MongoKnowledgeGraph::initializeBackend ( std::string_view  db_uri,
std::string_view  db_name = "knowrob",
std::string_view  collectionName = "triples" 
)

Initialize the knowledge graph with a MongoDB URI.

Parameters
db_urithe URI string used to connect to the database.
db_namethe name of the database.
collectionNamethe name of the collection for triples.
Returns
true on success

◆ initializeMongo() [1/2]

void knowrob::MongoKnowledgeGraph::initializeMongo ( const std::shared_ptr< mongo::Collection > &  tripleCollection)
protected

◆ initializeMongo() [2/2]

void MongoKnowledgeGraph::initializeMongo ( const std::shared_ptr< mongo::Collection > &  tripleCollection)
protected

Definition at line 147 of file MongoKnowledgeGraph.cpp.

147  {
149  // make sure s/p/o index is defined
150  tripleCollection_->createTripleIndex();
151  // a collection with just a single document used for querying
152  oneCollection_ = std::make_shared<Collection>(
153  tripleCollection_->connection(),
154  tripleCollection_->dbName().c_str(),
156  // Make sure there is one document in the "one" collection.
157  // The collection is used to initiate a pipeline for a single input document.
158  if (oneCollection_->empty()) {
159  Document oneDoc(bson_new());
160  bson_t scopeDoc, timeDoc;
161  bson_decimal128_t infinity, zero;
162  bson_decimal128_from_string(BSON_DECIMAL128_INF, &infinity);
163  bson_decimal128_from_string("0", &zero);
164  BSON_APPEND_DOCUMENT_BEGIN(oneDoc.bson(), "v_scope", &scopeDoc);
165  BSON_APPEND_DOCUMENT_BEGIN(&scopeDoc, "time", &timeDoc);
166  BSON_APPEND_DECIMAL128(&timeDoc, "since", &zero);
167  BSON_APPEND_DECIMAL128(&timeDoc, "until", &infinity);
168  bson_append_document_end(&scopeDoc, &timeDoc);
169  bson_append_document_end(oneDoc.bson(), &scopeDoc);
170  oneCollection_->storeOne(oneDoc);
171  }
172  // Create an object used for taxonomy operations
173  taxonomy_ = std::make_shared<MongoTaxonomy>(tripleCollection_, oneCollection_, vocabulary_);
174  // Add the connection to connection list
176 }
std::shared_ptr< mongo::Collection > oneCollection_
std::shared_ptr< mongo::MongoTaxonomy > taxonomy_

◆ insertAll() [1/2]

bool MongoKnowledgeGraph::insertAll ( const TripleContainerPtr triples)
overridevirtual

Add assertions to this backend.

Parameters
triplesa set of triples.
Returns
true on success

Implements knowrob::Storage.

Definition at line 249 of file MongoKnowledgeGraph.cpp.

249  {
250  ConnectionRAII scoped(this);
251  // only used in case triples do not specify origin field
252  auto &fallbackOrigin = vocabulary_->importHierarchy()->defaultGraph();
253  auto bulk = scoped.mongo.tripleCollection->createBulkOperation();
254  std::vector<MongoTaxonomy::StringPair> subClassAssertions;
255  std::vector<MongoTaxonomy::StringPair> subPropertyAssertions;
256 
257  std::for_each(triples->begin(), triples->end(),
258  [&](auto &data) {
259  MongoTriple mngTriple(vocabulary_, *data, fallbackOrigin,
260  vocabulary_->isTaxonomicProperty(data->predicate().data()));
261  bulk->pushInsert(mngTriple.document().bson());
262 
263  if (isSubClassOfIRI(data->predicate())) {
264  subClassAssertions.emplace_back(data->subject(), data->valueAsString());
265  } else if (isSubPropertyOfIRI(data->predicate())) {
266  subPropertyAssertions.emplace_back(data->subject(), data->valueAsString());
267  }
268  });
269  bulk->execute();
270 
271  taxonomy_->updateInsert(subClassAssertions, subPropertyAssertions);
272 
273  return true;
274 }
bool isSubPropertyOfIRI(std::string_view iri)
Definition: rdfs.cpp:12

◆ insertAll() [2/2]

bool knowrob::MongoKnowledgeGraph::insertAll ( const TripleContainerPtr triples)
overridevirtual

Add assertions to this backend.

Parameters
triplesa set of triples.
Returns
true on success

Implements knowrob::Storage.

◆ insertOne() [1/2]

bool MongoKnowledgeGraph::insertOne ( const Triple triple)
overridevirtual

Add an assertion to this backend.

Parameters
triplea triple.
Returns
true on success

Implements knowrob::Storage.

Definition at line 233 of file MongoKnowledgeGraph.cpp.

233  {
234  ConnectionRAII scoped(this);
235  auto &fallbackOrigin = vocabulary_->importHierarchy()->defaultGraph();
236  bool isTaxonomic = vocabulary_->isTaxonomicProperty(tripleData.predicate());
237  MongoTriple mngTriple(vocabulary_, tripleData, fallbackOrigin, isTaxonomic);
238  scoped.mongo.tripleCollection->storeOne(mngTriple.document());
239 
240  if (isSubClassOfIRI(tripleData.predicate())) {
241  taxonomy_->updateInsert({{tripleData.subject(), tripleData.valueAsString()}}, {});
242  } else if (isSubPropertyOfIRI(tripleData.predicate())) {
243  taxonomy_->updateInsert({}, {{tripleData.subject(), tripleData.valueAsString()}});
244  }
245 
246  return true;
247 }
bool isSubClassOfIRI(std::string_view iri)
Definition: rdfs.cpp:9

◆ insertOne() [2/2]

bool knowrob::MongoKnowledgeGraph::insertOne ( const Triple triple)
overridevirtual

Add an assertion to this backend.

Parameters
triplea triple.
Returns
true on success

Implements knowrob::Storage.

◆ isPersistent() [1/2]

bool knowrob::MongoKnowledgeGraph::isPersistent ( ) const
inlineoverridevirtual
Returns
true if the backend is persistent.

Implements knowrob::QueryableStorage.

Definition at line 110 of file MongoKnowledgeGraph.h.

110 { return true; }

◆ isPersistent() [2/2]

bool knowrob::MongoKnowledgeGraph::isPersistent ( ) const
inlineoverridevirtual
Returns
true if the backend is persistent.

Implements knowrob::QueryableStorage.

Definition at line 110 of file MongoKnowledgeGraph.h.

110 { return true; }

◆ isReadOnly() [1/2]

bool knowrob::MongoKnowledgeGraph::isReadOnly ( ) const
inline
Returns
true if only read operations are allowed.

Definition at line 65 of file MongoKnowledgeGraph.h.

65 { return isReadOnly_; }

◆ isReadOnly() [2/2]

bool knowrob::MongoKnowledgeGraph::isReadOnly ( ) const
inline
Returns
true if only read operations are allowed.

Definition at line 65 of file MongoKnowledgeGraph.h.

65 { return isReadOnly_; }

◆ iterate() [1/2]

void MongoKnowledgeGraph::iterate ( mongo::TripleCursor cursor,
const TripleVisitor visitor 
)
staticprotected

Definition at line 354 of file MongoKnowledgeGraph.cpp.

354  {
355  TripleView tripleData;
356  TriplePtr triplePtr;
357  triplePtr.ptr = &tripleData;
358  // Mongo cursor own the allocation, and the memory of a document will be deallocated by the cursor during iteration.
359  // @see https://mongoc.org/libmongoc/current/mongoc_cursor_next.html
360  // So it cannot be allowed that the visitor takes over ownership, hence owned is set to false.
361  triplePtr.owned = false;
362 
363  // iterate over matching documents
364  while (cursor.nextTriple(*triplePtr.ptr)) {
365  visitor(triplePtr);
366  }
367 }
bool nextTriple(Triple &tripleData, const bson_oid_t **tripleOID)
Triple * ptr
Definition: Triple.h:590

◆ iterate() [2/2]

static void knowrob::MongoKnowledgeGraph::iterate ( mongo::TripleCursor cursor,
const TripleVisitor visitor 
)
staticprotected

◆ lookup() [1/4]

BindingsCursorPtr MongoKnowledgeGraph::lookup ( const GraphTerm query)

Lookup up a path of matching triples. The lookup pipeline includes a step for each expression in the vector in the same order as the expressions are ordered in the vector.

Parameters
querya path query
Returns
a getAnswerCursor over matching triples

Definition at line 456 of file MongoKnowledgeGraph.cpp.

456  {
457  ConnectionRAII scoped(this);
458  return doLookup(query, scoped.mongo);
459 }
void query(const GraphQueryPtr &query, const BindingsHandler &callback) override

◆ lookup() [2/4]

mongo::BindingsCursorPtr knowrob::MongoKnowledgeGraph::lookup ( const GraphTerm query)

Lookup up a path of matching triples. The lookup pipeline includes a step for each expression in the vector in the same order as the expressions are ordered in the vector.

Parameters
querya path query
Returns
a getAnswerCursor over matching triples

◆ lookup() [3/4]

BindingsCursorPtr MongoKnowledgeGraph::lookup ( const TriplePattern query)

Lookup up all matching triples.

Parameters
querya triple pattern
Returns
a getAnswerCursor over matching triples

Definition at line 451 of file MongoKnowledgeGraph.cpp.

451  {
452  ConnectionRAII scoped(this);
453  return doLookup(query, scoped.mongo);
454 }

◆ lookup() [4/4]

mongo::BindingsCursorPtr knowrob::MongoKnowledgeGraph::lookup ( const TriplePattern query)

Lookup up all matching triples.

Parameters
querya triple pattern
Returns
a getAnswerCursor over matching triples

◆ match() [1/2]

void MongoKnowledgeGraph::match ( const TriplePattern query,
const TripleVisitor visitor 
)
overridevirtual
Parameters
querya framed triple pattern.
visitora function that is called for each matching framed triple.

Reimplemented from knowrob::QueryableStorage.

Definition at line 421 of file MongoKnowledgeGraph.cpp.

421  {
422  ConnectionRAII scoped(this);
423  bool b_isTaxonomicProperty;
424  if (query.propertyTerm()->termType() == TermType::ATOMIC) {
425  b_isTaxonomicProperty = vocabulary_->isTaxonomicProperty(((Atomic *) query.propertyTerm().get())->stringForm());
426  } else {
427  b_isTaxonomicProperty = false;
428  }
429  TripleCursor cursor(scoped.mongo.tripleCollection);
430  // filter documents by triple pattern
431  MongoTriplePattern mngQuery(query, b_isTaxonomicProperty, vocabulary_->importHierarchy());
432  cursor.filter(mngQuery.bson());
433  iterate(cursor, visitor);
434 }

◆ match() [2/2]

void knowrob::MongoKnowledgeGraph::match ( const TriplePattern query,
const TripleVisitor visitor 
)
overridevirtual
Parameters
querya framed triple pattern.
visitora function that is called for each matching framed triple.

Reimplemented from knowrob::QueryableStorage.

◆ query() [1/2]

void MongoKnowledgeGraph::query ( const GraphQueryPtr query,
const BindingsHandler callback 
)
overridevirtual

Submits a graph query to this storage.

Parameters
querya graph query
callbacka function that is called for each answer to the query.

Implements knowrob::QueryableStorage.

Definition at line 461 of file MongoKnowledgeGraph.cpp.

461  {
462  const bool onlyOneSol = (q->ctx()->queryFlags & QUERY_FLAG_ONE_SOLUTION);
463  ConnectionRAII scoped(this);
464  BindingsCursorPtr cursor = doLookup(*q->term(), scoped.mongo);
465  // NOTE: for some reason below causes a cursor error. looks like a bug in libmongoc to me!
466  //if(query->flags() & QUERY_FLAG_ONE_SOLUTION) { cursor->limit(1); }
467 
468  while (true) {
469  auto next = std::make_shared<Bindings>();
470  if (cursor->nextBindings(next)) callback(next);
471  else break;
472  if (onlyOneSol) break;
473  }
474 }
std::shared_ptr< BindingsCursor > BindingsCursorPtr
@ QUERY_FLAG_ONE_SOLUTION
Definition: QueryFlag.h:17

◆ query() [2/2]

void knowrob::MongoKnowledgeGraph::query ( const GraphQueryPtr query,
const BindingsHandler callback 
)
overridevirtual

Submits a graph query to this storage.

Parameters
querya graph query
callbacka function that is called for each answer to the query.

Implements knowrob::QueryableStorage.

◆ releaseStore() [1/2]

void MongoKnowledgeGraph::releaseStore ( mongo::TripleStore store) const
protected

Definition at line 89 of file MongoKnowledgeGraph.cpp.

89  {
90  std::lock_guard<std::mutex> lock(storeMutex_);
92  connections_.push_back(store);
93  }
94 }
#define MONGO_KG_NUM_KEEP_ALIVE

◆ releaseStore() [2/2]

void knowrob::MongoKnowledgeGraph::releaseStore ( mongo::TripleStore store) const
protected

◆ removeAll() [1/2]

bool MongoKnowledgeGraph::removeAll ( const TripleContainerPtr triples)
overridevirtual

Delete all matching statements from this backend.

Parameters
triplesa set of triples.

Implements knowrob::Storage.

Definition at line 293 of file MongoKnowledgeGraph.cpp.

293  {
294  ConnectionRAII scoped(this);
295  auto bulk = scoped.mongo.tripleCollection->createBulkOperation();
296  std::vector<MongoTaxonomy::StringPair> subClassAssertions;
297  std::vector<MongoTaxonomy::StringPair> subPropertyAssertions;
298 
299  std::for_each(triples->begin(), triples->end(),
300  [&](auto &data) {
301  MongoTriplePattern mngQuery(
302  TriplePattern(*data),
303  vocabulary_->isTaxonomicProperty(data->predicate()),
304  vocabulary_->importHierarchy());
305  bulk->pushRemoveOne(mngQuery.bson());
306 
307  if (isSubClassOfIRI(data->predicate())) {
308  subClassAssertions.emplace_back(data->subject(), data->valueAsString());
309  } else if (isSubPropertyOfIRI(data->predicate())) {
310  subPropertyAssertions.emplace_back(data->subject(), data->valueAsString());
311  }
312  });
313  bulk->execute();
314 
315  taxonomy_->updateRemove(subClassAssertions, subPropertyAssertions);
316 
317  return true;
318 }

◆ removeAll() [2/2]

bool knowrob::MongoKnowledgeGraph::removeAll ( const TripleContainerPtr triples)
overridevirtual

Delete all matching statements from this backend.

Parameters
triplesa set of triples.

Implements knowrob::Storage.

◆ removeAllWithOrigin() [1/2]

bool MongoKnowledgeGraph::removeAllWithOrigin ( std::string_view  origin)
overridevirtual

Delete all statements with a given origin from this backend.

Parameters
originthe origin of the statements to be deleted.

Implements knowrob::Storage.

Definition at line 328 of file MongoKnowledgeGraph.cpp.

328  {
329  return dropOrigin(graphName);
330 }
bool dropOrigin(std::string_view origin)

◆ removeAllWithOrigin() [2/2]

bool knowrob::MongoKnowledgeGraph::removeAllWithOrigin ( std::string_view  origin)
overridevirtual

Delete all statements with a given origin from this backend.

Parameters
originthe origin of the statements to be deleted.

Implements knowrob::Storage.

◆ removeOne() [1/2]

bool MongoKnowledgeGraph::removeOne ( const Triple triple)
overridevirtual

Delete the first matching statement from this backend.

Parameters
triplea triple.

Implements knowrob::Storage.

Definition at line 276 of file MongoKnowledgeGraph.cpp.

276  {
277  ConnectionRAII scoped(this);
278  MongoTriplePattern mngQuery(
279  TriplePattern(triple),
280  vocabulary_->isTaxonomicProperty(triple.predicate()),
281  vocabulary_->importHierarchy());
282  scoped.mongo.tripleCollection->removeOne(mngQuery.document());
283 
284  if (isSubClassOfIRI(triple.predicate())) {
285  taxonomy_->updateRemove({{triple.subject(), triple.valueAsString()}}, {});
286  } else if (isSubPropertyOfIRI(triple.predicate())) {
287  taxonomy_->updateRemove({}, {{triple.subject(), triple.valueAsString()}});
288  }
289 
290  return true;
291 }
virtual std::string_view valueAsString() const =0
virtual std::string_view subject() const =0
virtual std::string_view predicate() const =0

◆ removeOne() [2/2]

bool knowrob::MongoKnowledgeGraph::removeOne ( const Triple triple)
overridevirtual

Delete the first matching statement from this backend.

Parameters
triplea triple.

Implements knowrob::Storage.

◆ tripleCollection() [1/2]

auto knowrob::MongoKnowledgeGraph::tripleCollection ( )
inline
Returns
the collection for triples.

Definition at line 70 of file MongoKnowledgeGraph.h.

70 { return tripleCollection_; }

◆ tripleCollection() [2/2]

auto knowrob::MongoKnowledgeGraph::tripleCollection ( )
inline
Returns
the collection for triples.

Definition at line 70 of file MongoKnowledgeGraph.h.

70 { return tripleCollection_; }

Friends And Related Function Documentation

◆ ConnectionRAII

Definition at line 170 of file MongoKnowledgeGraph.h.

Member Data Documentation

◆ COLL_NAME_TESTS

const std::string MongoKnowledgeGraph::COLL_NAME_TESTS = "triples_test"
static

Definition at line 32 of file MongoKnowledgeGraph.h.

◆ COLL_NAME_TRIPLES

const std::string MongoKnowledgeGraph::COLL_NAME_TRIPLES = "triples"
static

Definition at line 31 of file MongoKnowledgeGraph.h.

◆ connections_

std::list< mongo::TripleStore > knowrob::MongoKnowledgeGraph::connections_
mutableprotected

Definition at line 137 of file MongoKnowledgeGraph.h.

◆ DB_NAME_KNOWROB

const std::string MongoKnowledgeGraph::DB_NAME_KNOWROB = "knowrob"
static

Definition at line 29 of file MongoKnowledgeGraph.h.

◆ DB_NAME_TESTS

const std::string MongoKnowledgeGraph::DB_NAME_TESTS = "knowrob_test"
static

Definition at line 30 of file MongoKnowledgeGraph.h.

◆ DB_URI_DEFAULT

const std::string MongoKnowledgeGraph::DB_URI_DEFAULT = "mongodb://localhost:27017"
static

Register the backend with the BackendManager

Definition at line 28 of file MongoKnowledgeGraph.h.

◆ isReadOnly_

bool knowrob::MongoKnowledgeGraph::isReadOnly_
protected

Definition at line 134 of file MongoKnowledgeGraph.h.

◆ oneCollection_

std::shared_ptr< mongo::Collection > knowrob::MongoKnowledgeGraph::oneCollection_
protected

Definition at line 132 of file MongoKnowledgeGraph.h.

◆ storeMutex_

std::mutex knowrob::MongoKnowledgeGraph::storeMutex_
mutableprotected

Definition at line 136 of file MongoKnowledgeGraph.h.

◆ taxonomy_

std::shared_ptr< mongo::MongoTaxonomy > knowrob::MongoKnowledgeGraph::taxonomy_
protected

Definition at line 133 of file MongoKnowledgeGraph.h.

◆ tripleCollection_

std::shared_ptr< mongo::Collection > knowrob::MongoKnowledgeGraph::tripleCollection_
protected

Definition at line 131 of file MongoKnowledgeGraph.h.


The documentation for this class was generated from the following files: