Connect to OrientDB with the Gremlin javascript driver - orientdb

I'm struggling to find an example using the current gremlin javascript driver with OrientDB. I can't get it to connect to OrientDB (already using the tinkerpop enabled version).
My sample code looks like this:
const gremlin = require("gremlin")
const DriverRemoteConnection = gremlin.driver.DriverRemoteConnection
const graph = new gremlin.structure.Graph()
const g = graph.traversal().withRemote(new DriverRemoteConnection('ws://localhost:8182/demodb'))
g.V().toList().then(function(data) {
console.log(data)
}).catch(function(err) {
console.log(err)
})
Does someone have any experience using those together? Thanks

If you want to connect OrientDB trough Gremlin try this:
Local -> gremlin> g = new OrientGraph("plocal:db_path/nomeDB")
In-Memory -> gremlin> g = new OrientGraph("memory:nomeDB")
Remote -> gremlin> g = new OrientGraph("remote:localhost/nomeDB")
Hope it helps
Regards

I dug a little bit. Gremlin Javascript driver does not support GraphSON3
https://github.com/jbmusso/gremlin-javascript/issues/109
Add this to your server.yaml serializer configuration in order to add support for v2
- { className: org.apache.tinkerpop.gremlin.driver.ser.GraphSONMessageSerializerGremlinV2d0, config: { ioRegistries: [org.apache.tinkerpop.gremlin.orientdb.io.OrientIoRegistry] }}
Then it should work

Try this:
import * as gremlin from 'gremlin';
const DriverRemoteConnection = gremlin.driver.DriverRemoteConnection;
const authenticator = new gremlin.driver.auth.PlainTextSaslAuthenticator(<db username>, <db password>);
const traversal = gremlin.process.AnonymousTraversalSource.traversal;
const g = traversal().withRemote(new DriverRemoteConnection('ws://localhost:8182/gremlin', {
authenticator: authenticator
}));
Notice the /gremlin in the url, not /demodb.
To point to demodb or another database modify the demodb.properties file in the config folder from OrientDB.
If you want you can create another properties file, just remember to point to it in the gremlin-server.yaml file.

Related

How to connect to mongodb database using Nextjs?

Trying to connect to my mongodb database in the latest version of Nextjs. Things have changed so much, so I don't longer know what to do.
There's an example of how to set up the connection here: https://github.com/vercel/next.js/tree/canary/examples/with-mongodb
They use this file:
//The mongodb.js file from the example
import { MongoClient } from 'mongodb'
const uri = process.env.MONGODB_URI
const options = {}
let client
let clientPromise
if (!process.env.MONGODB_URI) {
throw new Error('Please add your Mongo URI to .env.local')
}
if (process.env.NODE_ENV === 'development') {
// In development mode, use a global variable so that the value
// is preserved across module reloads caused by HMR (Hot Module Replacement).
if (!global._mongoClientPromise) {
client = new MongoClient(uri, options)
global._mongoClientPromise = client.connect()
}
clientPromise = global._mongoClientPromise
} else {
// In production mode, it's best to not use a global variable.
client = new MongoClient(uri, options)
clientPromise = client.connect()
}
// Export a module-scoped MongoClient promise. By doing this in a
// separate module, the client can be shared across functions.
export default clientPromise
However, they forgot to add how to actually use it. I can't even begin to figure it out.
//pages/api/user.js
import client from '/lib/mongodb.js'
export default async function handler(req, res) {
//How do I connect here?
}
And two bonus questions:
I used to do caching on my database connection. Is it not needed anymore?
What happened to the utils folder? It used to be special, in that it didn't send anything there to the client. Now everyone seem to use lib but I don't think there's anything special with it?
You can do like this:
const dbClient = await client;
const db = dbClient.db('db-name');
const collection = db.collection('collection-name');
// example to get a doc in collection
const doc = await collection.findOne({query:""}, {...options})

Is it possible to create a new gcloud SQL instance from code?

Is it possible to create a new gcloud SQL instance from code?
For an RnD project, I need to write a tool that is able to spin up and delete postgres database hosted with gcloud. I see this can be done for compute instances using node. I would preferbly like to be able to do it using node or python but am not tied down to any particilar lanauge.
Is this possible and do you have any suggestions?
Yes, The Cloud SQL instances.insert API Call can be used to create instances. However there is no nice nodejs package like #google-cloud/compute. Instead you muse use the the generic, alpha googleapis library. This looks something like:
const {google} = require('googleapis');
const sql = google.sql({version: 'v1beta4'});
async function main () {
const auth = new google.auth.GoogleAuth({scopes: ['https://www.googleapis.com/auth/sqlservice.admin']});
const authClient = await auth.getClient();
const project = "your-project-id-123";
dbinstance = {
// see https://cloud.google.com/sql/docs/postgres/admin-api/rest/v1beta4/instances#DatabaseInstance
// for parameters
};
const res = await sql.instances.insert({project: project, requestBody: dbinstance, auth: authClient});
// ...
}

Meteor check if index has been created without Mongo Shell

Has somebody found a way to check if an index has been created after calling _ensureIndex / createIndex without using the Mongo Shell but in Meteor server code?
I am writing a package test, where I want to assert, that the indices have been created during some package code execution.
I'm using this code to extend collection prototype for getting indexes synchronously:
getIndexes.js:
const Future = Npm.require('fibers/future');
Mongo.Collection.prototype.getIndexes = function() {
const raw = this.rawCollection();
const future = new Future();
raw.indexes(function(err, res) {
if(err) {
future.throw(err);
}
future.return(indexes);
});
return future.wait();
};

Meteor: Unique MongoDB URL for different users

I'm very keen to utilize Meteor as the framework for my next project. However, there is a requirement to keep customer data separated into different MongoDB instances for users from different customers.
I have read on this thread that it could be as simple as using this:
var d = new MongoInternals.RemoteCollectionDriver("<mongo url>");
C = new Mongo.Collection("<collection name>", { _driver: d });
However, I was dished this error on my server/server.js. I'm using meteor 0.9.2.2
with meteor-platform 1.1.0.
Exception from sub Ep9DL57K7F2H2hTBz Error: A method named '/documents/insert' is already defined
at packages/ddp/livedata_server.js:1439
at Function._.each._.forEach (packages/underscore/underscore.js:113)
at _.extend.methods (packages/ddp/livedata_server.js:1437)
at Mongo.Collection._defineMutationMethods (packages/mongo/collection.js:888)
at new Mongo.Collection (packages/mongo/collection.js:208)
at Function.Documents.getCollectionByMongoUrl (app/server/models/documents.js:9:30)
at null._handler (app/server/server.js:12:20)
at maybeAuditArgumentChecks (packages/ddp/livedata_server.js:1594)
at _.extend._runHandler (packages/ddp/livedata_server.js:943)
at packages/ddp/livedata_server.js:737
Can anyone be so kind as to enlighten me whether or not I have made a mistake somewhere?
Thanks.
Br,
Ethan
Edit: This is my server.js
Meteor.publish('userDocuments', function () {
// Get company data store's mongo URL here. Simulate by matching domain of user's email.
var user = Meteor.users.findOne({ _id: this.userId });
if (!user || !user.emails) return;
var email = user.emails[0].address;
var mongoUrl = (email.indexOf('#gmail.com') >= 0) ?
'mongodb://localhost:3001/company-a-db' :
'mongodb://localhost:3001/company-b-db';
// Return documents
return Documents.getCollectionByMongoUrl(mongoUrl).find();
});
and this is the server side model.js
Documents = function () { };
var documentCollections = { };
Documents.getCollectionByMongoUrl = function (url) {
if (!(url in documentCollections)) {
var driver = new MongoInternals.RemoteCollectionDriver(url);
documentCollections[url] = new Meteor.Collection("documents", { _driver: driver });
}
return documentCollections[url];
};
Observation: The first attempt to new a Meteor.Collection works fine. I can continue to use that collection multiple times. But when I log out and login as another user from another company (in this example by using an email that is not from #gmail.com), the error above is thrown.
Downloaded meteor's source codes and peeked into mongo package. There is a way to hack around having to declare different collection names on the mongodb server based on Hubert's suggestion.
In the server side model.js, I've made these adaptation:
Documents.getCollectionByMongoUrl = function (userId, url) {
if (!(userId in documentCollections)) {
var driver = new MongoInternals.RemoteCollectionDriver(url);
documentCollections[userId] = new Meteor.Collection("documents" + userId, { _driver: driver });
documentCollections[userId]._connection = driver.open("documents", documentCollections[userId]._connection);
}
return documentCollections[userId];
};
Super hack job here. Be careful when using this!!!!
I believe Meteor distinguish its collections internally by the name you pass to them as the first argument, so when you create the "documents" collection the second time, it tries to override the structure. Hence the error when trying to create the /documents/insert method the second time.
To work around this, you could apply a suffix to your collection name. So instead of:
new Meteor.Collection('documents', { _driver: driver });
you should try:
new Meteor.Collection('documents_' + userId, { _driver: driver })

Copy a database using mongo driver

I have the following code:
mongoServer.CopyDatabase(mongoDatabaseName, partitionName.Replace("__", string.Empty));
mongoServer.DropDatabase(mongoDatabaseName);
I obtain the following exception "NotImplementedException - The method or operation is not implemented."
How is it possible? I've wronged something? How can I copy my database?
The exception is correct as the CopyDatabase method isn't implemented. See the JIRA ticket for the history of the issue.
Instead, you need to directly invoke the 'copydb' command via a call to RunCommand on the admin database like is described in this answer. So something like:
var adminDB = Server.GetDatabase("admin");
var command = new CommandDocument(new List<BsonElement> {
new BsonElement("copydb", 1),
new BsonElement("fromhost", "localhost"),
new BsonElement("fromdb", mongoDatabaseName),
new BsonElement("todb", partitionName.Replace("__", string.Empty))
});
var result = adminDB.RunCommand(command);