Skip to content

Commit 89989e6

Browse files
author
Chris Wiechmann
committed
Added Index document method and search now has multiple exists
1 parent 803ef29 commit 89989e6

File tree

16 files changed

+739
-74
lines changed

16 files changed

+739
-74
lines changed

api-builder-plugin-fn-elasticsearch/CHANGELOG.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,11 @@ All notable changes to this project will be documented in this file.
44
The format is based on [Keep a Changelog](http://keepachangelog.com/)
55
and this project adheres to [Semantic Versioning](http://semver.org/).
66

7+
## [2.0.0] 2021-09-14
8+
### Changed
9+
- Search method now provides missingIndex & noResult exists making it easier to control your flow
10+
- New method Index document
11+
712
## [1.0.23] 2021-09-10
813
### Fixed
914
- No longer trying to read ca.pem

api-builder-plugin-fn-elasticsearch/config/elasticsearch.default.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,10 @@ module.exports = {
1818
// https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/7.x/client-configuration.html
1919
maxRetries: 5,
2020
requestTimeout: 60000,
21-
//ssl: {
21+
ssl: {
2222
// ca: fs.readFileSync('./cacert.pem'),
23-
// rejectUnauthorized: false
24-
//}
23+
rejectUnauthorized: ("false" == process.env.ELASTIC_SSL_REJECT_UNAUTHORIZED) ? false : true
24+
}
2525
},
2626
// The connection to Elasticsearch is validated on API-Builder startup by default
2727
// It can be disabled by setting this to false.

api-builder-plugin-fn-elasticsearch/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@axway-api-builder-ext/api-builder-plugin-fn-elasticsearch",
3-
"version": "1.0.23",
3+
"version": "2.0.0",
44
"description": "Integrate Elasticsearch into your API-Builder flow to combine search data for instance with other data available in your flow.",
55
"author": "Chris Wiechmann <cwiechmann@axway.com> (http://www.axway.com)",
66
"license": "Apache-2.0",
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
const { ElasticsearchClient } = require('./ElasticsearchClient');
2+
3+
/**
4+
* Action method.
5+
* @param {object} req - The flow request context passed in at runtime. The
6+
* parameters are resolved as `req.params` and the available authorization
7+
* credentials are passed in as `req.authorizations`.
8+
* @param {object} outputs - A set of output callbacks. Use it to signal an
9+
* event and pass the output result back to the runtime. Only use an
10+
* output callback once and only after all asyncronous tasks complete.
11+
* @param {object} options - The additional options provided from the flow
12+
* engine.
13+
* @param {object} The logger from API Builder that can be used to log messages
14+
* to the console. See https://docs.axway.com/bundle/API_Builder_4x_allOS_en/page/logging.html
15+
*
16+
* @return {undefined}
17+
*/
18+
19+
async function indexDocument(params, options) {
20+
const { index, body, addTimestamp} = params;
21+
const elasticSearchConfig = options.pluginConfig.elastic;
22+
if (typeof elasticSearchConfig.node === 'undefined' && typeof elasticSearchConfig.nodes === 'undefined') {
23+
options.logger.error('Elasticsearch configuration is invalid: nodes or node is missing.');
24+
throw new Error('Elasticsearch configuration is invalid: nodes or node is missing.');
25+
}
26+
27+
// Getting the client (which is a singleton)
28+
var client = new ElasticsearchClient(elasticSearchConfig).client;
29+
30+
if(!index) {
31+
throw new Error(`Missing required parameter: index`);
32+
}
33+
if(!body) {
34+
throw new Error(`Missing required parameter: body`);
35+
}
36+
// If a timestamp field is given, add the timestamp to the body
37+
if(addTimestamp) {
38+
body[addTimestamp] = Date.now();
39+
delete params.addTimestamp;
40+
}
41+
42+
var result;
43+
try {
44+
result = await client.index( params, { ignore: [404], maxRetries: 3 });
45+
} catch (ex) {
46+
if(ex instanceof Error) throw ex;
47+
throw new Error(JSON.stringify(ex));
48+
}
49+
if(result.statusCode!=201) {
50+
throw new Error(JSON.stringify(result));
51+
}
52+
return result;
53+
}
54+
55+
module.exports = {
56+
indexDocument
57+
};

api-builder-plugin-fn-elasticsearch/src/actions/search.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@ async function search(params, options) {
7878
addQueryParam("version");
7979

8080
options.logger.debug(`Using elastic search body: ${JSON.stringify(searchBody)}`);
81+
8182
var queryResult;
8283
try {
8384
queryResult = await client.search( searchBody, { ignore: [404], maxRetries: 3 });
@@ -86,6 +87,14 @@ async function search(params, options) {
8687
throw new Error(JSON.stringify(ex));
8788
}
8889

90+
if(queryResult.statusCode === 404 && queryResult.body.error.type == "index_not_found_exception") {
91+
return options.setOutput('missingIndex', queryResult);
92+
}
93+
94+
if(queryResult.body.hits.total.value === 0) {
95+
return options.setOutput('noResult', queryResult);
96+
}
97+
8998
return queryResult;
9099

91100
function addQueryParam(field) {

api-builder-plugin-fn-elasticsearch/src/flow-nodes.yml

Lines changed: 168 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -360,21 +360,31 @@ flow-nodes:
360360
schema:
361361
default: false
362362
type: boolean
363-
returns:
364-
name: Next
365-
description: Context variable will contain the Elasticsearch result
366-
context: $.result
367-
schema:
368-
type: object
369-
throws:
370-
name: Error
371-
description: An unexpected error was encountered.
372-
context: $.error
373-
schema:
374-
type: object
375-
properties:
376-
message:
377-
type: string
363+
outputs:
364+
next:
365+
name: Next
366+
description: Variable contains the Elasticsearch result
367+
context: $.result
368+
schema:
369+
type: object
370+
noResult:
371+
name: No result
372+
description: Exit used if the query result contains no hits.
373+
context: $.result
374+
schema:
375+
type: object
376+
missingIndex:
377+
name: Missing index
378+
description: Exit used if the index does not exists in Elasticsearch.
379+
context: $.error
380+
schema:
381+
type: object
382+
error:
383+
name: Error
384+
description: An unexpected error happened
385+
context: $.error
386+
schema:
387+
type: object
378388

379389
getTemplate:
380390
name: Get Index Template
@@ -484,6 +494,148 @@ flow-nodes:
484494
schema:
485495
type: object
486496

497+
indexDocument:
498+
name: Index document
499+
description: This method sends a document to Elasticsearch
500+
parameters:
501+
index:
502+
name: Index-Name
503+
description: The name of the index
504+
required: true
505+
schema:
506+
type: string
507+
body:
508+
name: Body
509+
description: "Body of the document to index"
510+
required: true
511+
schema:
512+
type: object
513+
id:
514+
name: ID
515+
description: Document ID. If not given Elasticsearch creates a unique document ID.
516+
required: false
517+
schema:
518+
type: string
519+
addTimestamp:
520+
name: Add timestamp
521+
description: If a field name (e.g. @timestamp) is given, the flow-node will add the current Unix epoch time to the body of the document.
522+
required: false
523+
initialType: string
524+
schema:
525+
type: string
526+
waitForActiveShards:
527+
name: Wait for active shards
528+
description: Sets the number of shard copies that must be active before proceeding with the index operation. Defaults to 1, meaning the primary shard only. Set to all for all shard copies, otherwise set to any non-negative value less than or equal to the total number of copies for the shard (number of replicas + 1)
529+
required: false
530+
group: Advanced Options
531+
schema:
532+
type: string
533+
opType:
534+
name: Explicit operation type
535+
description: Defaults to index for requests with an explicit document ID, and to `create`for requests without an explicit document ID
536+
required: false
537+
group: Advanced Options
538+
initialType: string
539+
schema:
540+
type: string
541+
enum:
542+
- index
543+
- create
544+
refresh:
545+
name: Refresh
546+
description: If true then refresh the affected shards to make this operation visible to search, if wait_for then wait for a refresh to make this operation visible to search, if false (the default) then do nothing with refreshes.
547+
required: false
548+
group: Advanced Options
549+
initialType: string
550+
schema:
551+
type: string
552+
enum:
553+
- true
554+
- false
555+
- wait_for
556+
routing:
557+
name: Routing
558+
description: Specific routing value
559+
required: false
560+
group: Advanced Options
561+
initialType: string
562+
schema:
563+
type: string
564+
timeout:
565+
name: Timeout
566+
description: Explicit operation timeout. https://www.elastic.co/guide/en/elasticsearch/reference/7.x/common-options.html#time-units
567+
required: false
568+
group: Advanced Options
569+
initialType: string
570+
schema:
571+
type: string
572+
version:
573+
name: Version
574+
description: Explicit version number for concurrency control
575+
required: false
576+
group: Advanced Options
577+
initialType: string
578+
schema:
579+
type: string
580+
versionType:
581+
name: Version Type
582+
description: Specific version type
583+
required: false
584+
group: Advanced Options
585+
initialType: string
586+
schema:
587+
type: string
588+
enum:
589+
- internal
590+
- external
591+
- external_gte
592+
ifSeqNo:
593+
name: Version Type
594+
description: Only perform the index operation if the last operation that has changed the document has the specified sequence number
595+
required: false
596+
group: Advanced Options
597+
schema:
598+
type: number
599+
ifPrimaryTerm:
600+
name: If primary term
601+
description: Only perform the index operation if the last operation that has changed the document has the specified primary term
602+
required: false
603+
group: Advanced Options
604+
schema:
605+
type: number
606+
pipeline:
607+
name: Pipeline
608+
description: The pipeline id to preprocess incoming documents with
609+
required: false
610+
group: Advanced Options
611+
initialType: string
612+
schema:
613+
type: string
614+
requireAlias:
615+
name: Require alias
616+
description: When true, requires destination to be an alias. Default is false
617+
required: false
618+
group: Advanced Options
619+
initialType: boolean
620+
schema:
621+
default: false
622+
type: boolean
623+
returns:
624+
name: Next
625+
description: The response returned from Elasticsearch for the indexed document
626+
context: $.result
627+
schema:
628+
type: object
629+
throws:
630+
name: Error
631+
description: An unexpected error was encountered.
632+
context: $.error
633+
schema:
634+
type: object
635+
properties:
636+
message:
637+
type: string
638+
487639
getMapping:
488640
name: Get Index Mapping
489641
description: Gets an index mapping from Elasticsearch
@@ -830,7 +982,7 @@ flow-nodes:
830982
type: string
831983
alias:
832984
name: Alias name
833-
description: The alias for the index. If an index configuration is given, this alias name is merged into it.
985+
description: The alias for the index. If an index configuration is given, this alias name is merged into it. Please note, that the index- and alias-name must be different.
834986
required: false
835987
initialType: string
836988
schema:

api-builder-plugin-fn-elasticsearch/src/index.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ const { getILMPolicy, putILMPolicy } = require('./actions/ilmPolicy');
77
const { getRollupJobs, putRollupJob } = require('./actions/rollupJobs');
88
const { putTransform } = require('./actions/transform');
99
const { indicesRollover, indicesCreate, indicesExists } = require('./actions/indices');
10+
const { indexDocument } = require('./actions/indexDocument');
1011
const { ElasticsearchClient } = require('./actions/ElasticsearchClient');
1112
const { isDeveloperMode } = require('./utils');
1213

@@ -53,7 +54,8 @@ async function getPlugin(pluginConfig, options) {
5354
indicesRollover,
5455
indicesCreate,
5556
indicesExists,
56-
putTransform
57+
putTransform,
58+
indexDocument
5759
}, pluginConfig);
5860
const plugin = sdk.getPlugin();
5961
return plugin;

api-builder-plugin-fn-elasticsearch/test/basic/test-config.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ describe('Basic: flow-node elasticsearch', () => {
1212
let plugin;
1313
let flowNode;
1414

15-
var client = new ElasticsearchClient({nodes:'http://api-env:9200'}).client;
15+
var client = new ElasticsearchClient({nodes:'https://api-env:9200', ssl: { rejectUnauthorized: false }}).client;
1616
beforeEach(async () => {
1717
plugin = await MockRuntime.loadPlugin(getPlugin, validConfig);
1818
validConfig.validateConnection = false;

api-builder-plugin-fn-elasticsearch/test/config/basic-config.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ module.exports = {
44
pluginConfig: {
55
'@axway-api-builder-ext/api-builder-plugin-fn-elasticsearch': {
66
'elastic': {
7-
node: 'http://api-env:9200',
7+
node: 'https://api-env:9200',
88
auth: {
99
/* Use an API-Key
1010
apiKey: process.env.ELASTIC_API_KEY

0 commit comments

Comments
 (0)