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

64 lines
1.2 KiB
JavaScript
Raw Normal View History

2020-11-26 18:03:18 +01:00
const { Client } = require("@elastic/elasticsearch")
2021-01-11 18:18:22 +01:00
const SCHEMA = {
datasource: {
url: {
type: "string",
required: true,
default: "localhost",
},
index: {
type: "string",
required: true,
},
2020-11-26 18:03:18 +01:00
},
query: {
2021-01-11 18:18:22 +01:00
json: {
type: "json",
required: true,
},
2020-11-26 18:03:18 +01:00
},
}
class ElasticSearchIntegration {
constructor(config) {
this.config = config
this.client = new Client({ node: config.url })
}
async create(document) {
try {
const result = await this.client.index({
index: this.config.index,
body: JSON.parse(document),
})
return [result]
} catch (err) {
console.error("Error writing to elasticsearch", err)
throw err
} finally {
await this.client.close()
}
}
async read(query) {
2020-11-26 18:03:18 +01:00
try {
const result = await this.client.search({
index: this.config.index,
body: JSON.parse(query),
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()
}
}
}
module.exports = {
2021-01-11 18:18:22 +01:00
schema: SCHEMA,
2020-11-26 18:03:18 +01:00
integration: ElasticSearchIntegration,
}