budibase/packages/server/src/integrations/elasticsearch.js

141 lines
3.0 KiB
JavaScript
Raw Normal View History

2020-11-26 18:03:18 +01:00
const { Client } = require("@elastic/elasticsearch")
const { QUERY_TYPES, FIELD_TYPES } = require("./Integration")
2020-11-26 18:03:18 +01:00
2021-01-11 18:18:22 +01:00
const SCHEMA = {
2021-01-15 18:29:46 +01:00
docs:
"https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/index.html",
description:
"Elasticsearch is a search engine based on the Lucene library. It provides a distributed, multitenant-capable full-text search engine with an HTTP web interface and schema-free JSON documents.",
friendlyName: "ElasticSearch",
2021-01-11 18:18:22 +01:00
datasource: {
url: {
type: "string",
required: true,
default: "http://localhost:9200",
2021-01-11 18:18:22 +01:00
},
2020-11-26 18:03:18 +01:00
},
query: {
create: {
type: QUERY_TYPES.FIELDS,
customisable: true,
fields: {
index: {
type: FIELD_TYPES.STRING,
required: true,
},
},
},
read: {
type: QUERY_TYPES.FIELDS,
customisable: true,
fields: {
index: {
type: FIELD_TYPES.STRING,
required: true,
},
},
},
update: {
type: QUERY_TYPES.FIELDS,
customisable: true,
fields: {
id: {
type: FIELD_TYPES.STRING,
required: true,
},
index: {
type: FIELD_TYPES.STRING,
required: true,
},
},
},
delete: {
type: QUERY_TYPES.FIELDS,
fields: {
index: {
type: FIELD_TYPES.STRING,
required: true,
},
id: {
type: FIELD_TYPES.STRING,
required: true,
},
},
2021-01-11 18:18:22 +01:00
},
2020-11-26 18:03:18 +01:00
},
}
class ElasticSearchIntegration {
constructor(config) {
this.config = config
this.client = new Client({ node: config.url })
}
2021-01-13 17:39:47 +01:00
async create(query) {
const { index, json } = query
try {
const result = await this.client.index({
index,
body: json,
})
return result.body
} catch (err) {
console.error("Error writing to elasticsearch", err)
throw err
} finally {
await this.client.close()
}
}
async read(query) {
const { index, json } = query
2020-11-26 18:03:18 +01:00
try {
const result = await this.client.search({
index: index,
body: json,
2020-11-26 18:03:18 +01:00
})
return result.body.hits.hits.map(({ _source }) => _source)
2020-11-26 18:34:15 +01:00
} catch (err) {
console.error("Error querying elasticsearch", err)
throw err
2020-11-26 18:03:18 +01:00
} finally {
await this.client.close()
}
}
async update(query) {
const { id, index, json } = query
try {
const result = await this.client.update({
id,
index,
body: json,
})
return result.body
} catch (err) {
console.error("Error querying elasticsearch", err)
throw err
} finally {
await this.client.close()
}
}
async delete(query) {
try {
const result = await this.client.delete(query)
return result.body
} catch (err) {
console.error("Error deleting from elasticsearch", err)
throw err
} finally {
await this.client.close()
}
}
2020-11-26 18:03:18 +01:00
}
module.exports = {
2021-01-11 18:18:22 +01:00
schema: SCHEMA,
2020-11-26 18:03:18 +01:00
integration: ElasticSearchIntegration,
}