Skip to content

Commit

Permalink
[index_pattern_management]: Replace calls to `/elasticsearch/_msearch…
Browse files Browse the repository at this point in the history
…` with internal route. (elastic#77564)
  • Loading branch information
lukeelmers committed Sep 16, 2020
1 parent 375b7ff commit b25d852
Show file tree
Hide file tree
Showing 9 changed files with 361 additions and 83 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ export class TestScript extends Component<TestScriptProps, TestScriptState> {
}

previewScript = async (searchContext?: { query?: Query | undefined }) => {
const { indexPattern, lang, name, script, executeScript } = this.props;
const { indexPattern, name, script, executeScript } = this.props;

if (!script || script.length === 0) {
return;
Expand All @@ -104,7 +104,6 @@ export class TestScript extends Component<TestScriptProps, TestScriptState> {

const scriptResponse = await executeScript({
name: name as string,
lang,
script,
indexPatternTitle: indexPattern.title,
query,
Expand All @@ -122,7 +121,7 @@ export class TestScript extends Component<TestScriptProps, TestScriptState> {

this.setState({
isLoading: false,
previewData: scriptResponse.hits.hits.map((hit: any) => ({
previewData: scriptResponse.hits?.hits.map((hit: any) => ({
_id: hit._id,
...hit._source,
...hit.fields,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -784,7 +784,6 @@ export class FieldEditor extends PureComponent<FieldEdiorProps, FieldEditorState

const isValid = await isScriptValid({
name: field.name,
lang: field.lang as string,
script: field.script as string,
indexPatternTitle: indexPattern.title,
http: this.context.services.http,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,72 +17,50 @@
* under the License.
*/

import { Query } from 'src/plugins/data/public';
import { HttpStart } from 'src/core/public';
import { ExecuteScriptParams, ExecuteScriptResult } from '../types';

export const executeScript = async ({
name,
lang,
script,
indexPatternTitle,
query,
additionalFields = [],
http,
}: ExecuteScriptParams): Promise<ExecuteScriptResult> => {
// Using _msearch because _search with index name in path dorks everything up
const header = {
index: indexPatternTitle,
ignore_unavailable: true,
};

const search = {
query: {
match_all: {},
} as Query['query'],
script_fields: {
[name]: {
script: {
lang,
source: script,
},
},
},
_source: undefined as string[] | undefined,
size: 10,
timeout: '30s',
};

if (additionalFields.length > 0) {
search._source = additionalFields;
}

if (query) {
search.query = query;
}

const body = `${JSON.stringify(header)}\n${JSON.stringify(search)}\n`;
const esResp = await http.fetch('/elasticsearch/_msearch', { method: 'POST', body });
// unwrap _msearch response
return esResp.responses[0];
return http
.post('/internal/index-pattern-management/preview_scripted_field', {
body: JSON.stringify({
index: indexPatternTitle,
name,
script,
query,
additionalFields,
}),
})
.then((res) => ({
status: res.statusCode,
hits: res.body.hits,
}))
.catch((err) => ({
status: err.statusCode,
error: err.body.attributes.error,
}));
};

export const isScriptValid = async ({
name,
lang,
script,
indexPatternTitle,
http,
}: {
name: string;
lang: string;
script: string;
indexPatternTitle: string;
http: HttpStart;
}) => {
const scriptResponse = await executeScript({
name,
lang,
script,
indexPatternTitle,
http,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ export interface Sample {

export interface ExecuteScriptParams {
name: string;
lang: string;
script: string;
indexPatternTitle: string;
query?: Query['query'];
Expand All @@ -38,7 +37,7 @@ export interface ExecuteScriptParams {

export interface ExecuteScriptResult {
status: number;
hits: { hits: any[] };
hits?: { hits: any[] };
error?: any;
}

Expand Down
41 changes: 4 additions & 37 deletions src/plugins/index_pattern_management/server/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,50 +18,17 @@
*/

import { PluginInitializerContext, CoreSetup, Plugin } from 'src/core/server';
import { schema } from '@kbn/config-schema';

import { registerPreviewScriptedFieldRoute, registerResolveIndexRoute } from './routes';

export class IndexPatternManagementPlugin implements Plugin<void, void> {
constructor(initializerContext: PluginInitializerContext) {}

public setup(core: CoreSetup) {
const router = core.http.createRouter();

router.get(
{
path: '/internal/index-pattern-management/resolve_index/{query}',
validate: {
params: schema.object({
query: schema.string(),
}),
query: schema.object({
expand_wildcards: schema.maybe(
schema.oneOf([
schema.literal('all'),
schema.literal('open'),
schema.literal('closed'),
schema.literal('hidden'),
schema.literal('none'),
])
),
}),
},
},
async (context, req, res) => {
const queryString = req.query.expand_wildcards
? { expand_wildcards: req.query.expand_wildcards }
: null;
const result = await context.core.elasticsearch.legacy.client.callAsCurrentUser(
'transport.request',
{
method: 'GET',
path: `/_resolve/index/${encodeURIComponent(req.params.query)}${
queryString ? '?' + new URLSearchParams(queryString).toString() : ''
}`,
}
);
return res.ok({ body: result });
}
);
registerPreviewScriptedFieldRoute(router);
registerResolveIndexRoute(router);
}

public start() {}
Expand Down
21 changes: 21 additions & 0 deletions src/plugins/index_pattern_management/server/routes/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

export * from './preview_scripted_field';
export * from './resolve_index';
Loading

0 comments on commit b25d852

Please sign in to comment.