MindsDB JavaScript SDK
The MindsDB JavaScript SDK allows you to unlock the power of machine learning right inside your web applications. We provide interfaces to perform most MindsDB operations, such as training and querying models, and connecting your own datasources to MindsDB.
Getting Started
If you haven't already, make sure to create a MindsDB account to use with the SDK.
Installation
npm install --save mindsdb-js-sdk
We have full TypeScript support. Just import the types you need directly. For example:
import { Database, Model, ModelPrediction, Project, Table, View } from 'mindsdb-js-sdk';
Usage Examples
Connecting to MindsDB
Before performing any operations, you must connect to MindsDB. By default, all operations will go through MindsDB Cloud REST APIs, but you can use a self-hosted version of MindsDB as well. In future releases, we will support connecting directly to MySQL instances.
MindsDB Cloud:
import MindsDB from 'mindsdb-js-sdk';
try {
await MindsDB.connect({
user: 'mindsdbuser@gmail.com',
password: 'mypassword'
});
} catch(error) {
}
MindsDB Pro:
import MindsDB from 'mindsdb-js-sdk';
try {
await MindsDB.connect({
host: 'http://<YOUR_INSTANCE_IP>',
user: 'mindsdbuser@gmail.com',
password: 'mypassword'
});
} catch(error) {
}
Self-hosted
import MindsDB from 'mindsdb-js-sdk';
try {
await MindsDB.connect({
host: 'http://127.0.0.1:47334'
});
} catch(error) {
}
Using your own Axios instance. See src/util/http.ts for the default instance we use.
import MindsDB from 'mindsdb-js-sdk';
import axios from 'axios';
const customAxios = axios.create({
timeout: 1000,
});
try {
await MindsDB.connect({
user: mindsdbuser@gmail.com,
password: mypassword,
httpClient: customAxios
});
} catch(error) {
}
Connecting a Database to MindsDB
The following code example assumes you already imported and connected to MindsDB.
You can connect to many database integrations through MindsDB. For example, to connect to a Postgres database:
const connectionParams = {
'user': 'postgres',
'port': 15093,
'password': 'password',
'host': '127.0.0.1',
'database': 'postgres'
}
try {
const pgDatabase = await MindsDB.Databases.createDatabase(
'psql_datasource',
'postgres',
connectionParams);
} catch (error) {
}
Getting & Deleting a Database
const dbToDelete = await MindsDB.Databases.getDatabase('useless_db');
if (dbToDelete) {
try {
await dbToDelete.delete();
} catch (error) {
}
}
Running SQL Queries
The following code example assumes you already imported and connected to MindsDB.
When directly using SQL queries, we recommend escaping them when possible using libraries like mysql.
const user = 'raw_unsafe_username'
const query = `SELECT * FROM my_db.customer_data WHERE user=${mysql.escape(user)}`;
try {
const queryResult = await MindsDB.SQL.runQuery(query);
if (queryResult.rows.length > 0) {
const matchingUserRow = queryResult.rows[0];
}
} catch (error) {
}
Getting Projects
The following code examples assumes you already imported and connected to MindsDB.
const allProjects = await MindsDB.Projects.getAllProjects();
allProjects.forEach(p => {
console.log(p.name);
});
Training & Querying Models
The following code example assumes you already imported and connected to MindsDB.
See full training options docs
See full query options docs and full batch query options docs
Simple queries:
const regressionTrainingOptions = {
select: 'SELECT * FROM demo_data.home_rentals',
integration: 'example_db'
};
try {
let homeRentalPriceModel = await MindsDB.Models.trainModel(
'home_rentals_model',
'rental_price',
'mindsdb',
regressionTrainingOptions);
while (homeRentalPriceModel.status === 'training') {
homeRentalPriceModel = await MindsDB.Models.getModel('home_rentals_model', 'mindsdb');
}
const queryOptions = {
where: [
'sqft = 823',
'location = "good"',
'neighborhood = "downtown"',
'days_on_market = 10'
]
}
const rentalPricePrediction = homeRentalPriceModel.query(queryOptions);
console.log(rentalPricePrediction.value);
console.log(rentalPricePrediction.explain);
console.log(rentalPricePrediction.data);
} catch (error) {
}
A more complex example using batch querying:
const timeSeriesTrainingOptions = {
integration: 'example_db',
select: 'SELECT * FROM demo_data.house_sales',
orderBy: 'saledate',
groupBy: 'bedrooms',
window: 8,
horizon: 4,
using: {
'key': 'value',
'labels': ['house-label', 'test-label'],
'model.args': {
'submodels': [{
'module': 'LightGBM',
'args': {
'stop_after': 12,
'fit_on_dev': true
}
}]
}
}
}
try {
const houseSalesForecastModel = await MindsDB.Models.trainModel(
'house_sales_model',
'rental_price',
'mindsdb',
timeSeriesTrainingOptions);
const modelDescription = await houseSalesForecastModel.describe();
console.log(modelDescription);
const queryOptions = {
join: 'example_db.demo_data.house_sales',
where: ['t.saledate > LATEST', 't.type = "house"'],
limit: 4
}
const rentalPriceForecasts = await houseSalesForecastModel.batchQuery(queryOptions);
rentalPriceForecasts.forEach(f => {
console.log(f.value);
console.log(f.explain);
console.log(f.data);
})
} catch (error) {
}
Retraining & Adjusting Models
The following code example assumes you already imported and connected to MindsDB.
See full training options docs
See full adjust options docs
Retraining:
const homeRentalPriceModel = await MindsDB.Models.getModel('home_rentals_model', 'mindsdb');
if (homeRentalPriceModel.updateStatus === 'available') {
try {
await homeRentalPriceModel.retrain();
} catch (error) {
}
}
Adjusting:
const homeRentalPriceModel = await MindsDB.Models.getModel('home_rentals_model', 'mindsdb');
const adjustSelect = 'SELECT * FROM demo_data.home_rentals WHERE days_on_market >= 10';
const params = { 'key' : 'value' }
try {
await homeRentalPriceModel.adjust(
{ integration: 'example_db', select: adjustSelect, using: params });
} catch (error) {
}
Creating Views
After you create a view, you can query it by including it in SELECT statements as if it's a table.
The following code example assumes you already imported and connected to MindsDB.
const viewSelect = `SELECT t.sqft, t.location, m.rental_price
FROM example_db.home_rentals_data as t
JOIN mindsdb.home_rentals_model as m
`;
try {
const predictionsView = await MindsDB.Views.createView(
'predictions_view',
'mindsdb',
viewSelect);
} catch (error) {
}
Contributing
Being part of the core MindsDB team is accessible to anyone who is motivated and wants to be part of that journey!
Please see below how to contribute to the project, also refer to the contributing documentation.
How Can You Help Us?
- Report a bug
- Improve documentation
- Discuss the code implementation
- Submit a bug fix
- Propose new features
- Test the SDK
Code Contributions
In general, we follow the "fork-and-pull" Git workflow.
- Fork the mindsdb-js-sdk repository
- Clone the repository
- Make changes and commit them
- Push your local branch to your fork
- Submit a Pull request so that we can review your changes
- Write a commit message
Contributor Code of Conduct
Please note that this project is released with a Contributor Code of Conduct. By participating in this project, you agree to abide by its terms.
Join our mission of democratizing machine learning!
If you have additional questions or you want to chat with the MindsDB core team, please join our Slack community.
To get updates on MindsDB’s latest announcements, releases, and events, sign up for our Monthly Community Newsletter.