简体   繁体   English

Python (Jupyter) -> Vega -> Kibana?

[英]Python (Jupyter) -> Vega -> Kibana?

So we want to leverage the data-science and visualization strengths of Python on our ELK data and then use the Elastic API to send the resulting visualization to update a dashboard.因此,我们希望在我们的 ELK 数据上利用 Python 的数据科学和可视化优势,然后使用 Elastic API 发送生成的可视化结果以更新仪表板。

There are plenty of resources discussing this, only one of which actually provided a working example, however they leveraged now deprecated security bypasses, more of a hack.有很多资源讨论这个问题,其中只有一个实际提供了一个工作示例,但是他们利用了现在已弃用的安全绕过,更多的是黑客攻击。 Specifically, this refers to setting the index name to .kibana , which now results in the error:具体来说,这是指将索引名称设置为.kibana ,现在会导致错误:

AuthorizationException: AuthorizationException(403, 'security_exception', 'action [indices:data/write/bulk[s]] is unauthorized for user [elastic] with roles [superuser] on indices [.kibana_8.1.2_001,.kibana], this action is granted by the index privileges [create_doc,create,delete,index,write,all]')

We think this must be possible through normal API usage without disabling any security settings.我们认为这一定可以通过正常的 API 使用而无需禁用任何安全设置。 We did try adding a user with every possible permission added, and it could not perform this action during our testing.我们确实尝试添加一个用户,并添加所有可能的权限,但在我们的测试期间它无法执行此操作。

Here's the example referred to as well as the overarching project which inspired us to try this . 这是引用的示例以及启发我们尝试这个的总体项目

在此处输入图像描述

Note that Vega is now a default feature of Kibana rather than a plugin, so this workflow should be even more viable now.请注意,Vega现在是 Kibana 的默认功能而不是插件,因此此工作流程现在应该更加可行。

So our code goes like this:所以我们的代码是这样的:

import eland as ed
import datetime
import altair as alt
import eland as ed
import json
import numpy as np
import matplotlib.pyplot as plt
import vega_datasets
from elasticsearch import Elasticsearch

cloud_id = "secret"
http_auth = ("username", "password")
es = Elasticsearch(cloud_id=cloud_id, http_auth=http_auth)

data = vega_datasets.data
pd_df = data.cars()
chart = alt.Chart(pd_df).mark_point().encode(
    x='Miles_per_Gallon',
    y='Horsepower'
).interactive()

def saveVegaVis(client, index, visName, altairChart, resultSize=100, timeField=True):
    chart_json = json.loads(altairChart.to_json())
    visState = {
      "type": "vega",
      "aggs": [],
      "params": {
        "spec": json.dumps(chart_json, sort_keys=True, indent=4, separators=(',', ': ')),
      },
      "title": visName
    }
    visSavedObject={
        "visualization" : {
          "title" : visName,
          "visState" : json.dumps(visState, sort_keys=True, indent=4, separators=(',', ': ')),
          "uiStateJSON" : "{}",
          "description" : "",
          "version" : 1,
          "kibanaSavedObjectMeta" : {
            "searchSourceJSON" : json.dumps({
              "query": {
                "language": "kuery",
                "query": ""
              },
              "filter": []
            }),
          }
        },
        "type" : "visualization",
        "references" : [ ],
        "migrationVersion" : {
          "visualization" : "8.0.0"
        },
        "updated_at" : datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S.000Z")
    }


    return client.index(index=index,id='visualization:'+visName,body=visSavedObject)

saveVegaVis(es, 'test_visuals', 'def-vega-cars-1', chart, resultSize=1000)

After executing this code, we get a success message:执行此代码后,我们会收到一条成功消息:

ObjectApiResponse({'_index': 'test_visuals', '_id': 'visualization:def-vega-cars-1', '_version': 8, 'result': 'updated', '_shards': {'total': 2, 'successful': 1, 'failed': 0}, '_seq_no': 7, '_primary_term': 1})

But within ELK, the resulting object is not treated like a visualization, it's treated like a normal index entry.但在 ELK 中,生成的 object 并未被视为可视化,而是被视为普通索引条目。

We want it to show up like:我们希望它显示如下: 在此处输入图像描述

But rather, we can only see it as a normal index entry, like so:相反,我们只能将其视为普通索引条目,如下所示:

在此处输入图像描述

It seems to us that all of the traits for a visualization are there.在我们看来,可视化的所有特征都在那里。 To validate this, we exported a Vega visualization to observe the data structure (please excuse any oddities, the export leaves a lot of escape characters we tried to clean up):为了验证这一点,我们导出了一个 Vega 可视化来观察数据结构(请原谅任何奇怪的地方,导出留下了很多我们试图清理的转义字符):

{
    "attributes": {
        "description": "",
        "kibanaSavedObjectMeta": {
            "searchSourceJSON": {
                "query ":{
                    "query":"",
                    "language":"kuery"
                },
                "filter":[]
            }
        },
        "title": "TEST_VISUAL_PLZ_WORK",
        "uiStateJSON": "{}",
        "version": 1,
        "visState": {
        "title":"TEST_VISUAL_PLZ_WORK",
        "type":"vega",
        "aggs":[],
        "params":{
            "spec":" {
            "$schema": "https://vega.github.io/schema/vega/v3.json", n "width": 300, "height": 100, "data": [{
                n "name": "vals",
                n "values": [n {
                        "category": 50,
                        "count": 30
                    }, {
                        "category": 100,
                        "count": 80
                    }, {
                        "category": 150,
                        "count": 10
                    }, {
                        "category": 200,
                        "count": 50
                    }
                ]
            }], "marks": [{
                "type": "rect",
                "from": {
                    "data": "vals"
                },
                "encode": {
                    "update": {
                        "x": {
                            "field": "category"
                        },
                        "width": {
                            "value": 30
                        },
                        "y": {
                            "field": "count"
                        },
                        "y2": {
                            "value": 0
                        }
                    }
                }
            }]

        }
        "}}"
    },
    "coreMigrationVersion": "8.1.2",
    "id": "6e130cc0-b694-11ec-8df1-41f60ea92d87",
    "migrationVersion": {
        "visualization": "8.0.0"
    },
    "references": [],
    "type": "visualization",
    "updated_at": "2022-04-07T17:04:32.085Z",
    "version": "WzYxOTQsMl0="
} {
    "excludedObjects": [],
    "excludedObjectsCount": 0,
    "exportedCount": 1,
    "missingRefCount": 0,
    "missingReferences": []
}

And it seems our data structure matches this.看起来我们的数据结构与此匹配。

So are we going about this the wrong way?那么我们是不是走错了路? Is there some minor mistake?有什么小错误吗? Is it possible to do (without disabling security protocols / 'hacking' it)?是否可以这样做(不禁用安全协议/“破解”它)?

Looking at the example it looks like they drop it into a.kibana index which I know is a special index relating to kibana.查看示例,他们似乎将其放入 a.kibana 索引中,我知道这是与 kibana 相关的特殊索引。 You may want to change the index to that and see what happens.您可能希望将索引更改为该索引,然后看看会发生什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM