簡體   English   中英

將PowerShell JSON發布到ElasticSearch中

[英]Post PowerShell JSON into ElasticSearch

我正在嘗試通過PowerShell將一些數據推送到ElasticSearch中。 我將數據轉換為JSON,然后嘗試使用Invoke-WebRequestInvoke-RestMethod ,但是始終會收到格式錯誤的數據或不支持的內容類型錯誤。 我尚未創建索引,因為我相信它將為我創建索引。

任何人都可以協助解決我所缺少/做錯的事情嗎?

示例代碼:

$data = @()
$CustomObject = [pscustomobject]@{
        SqlInstance = "myserver1"
        Database = "mydb"
        Schema = "versioning"
        Name = "DataVersionHistory"
        IndexSpaceUsed = 0
        DataSpaceUsed = 0
        RowCount = 0
        };
$data += $CustomObject;
$CustomObject = [pscustomobject]@{
        SqlInstance = "myserver1"
        Database = "mydb"
        Schema = "versioning"
        Name = "VersionHistory"
        IndexSpaceUsed = 10
        DataSpaceUsed = 25
        RowCount = 3000
        };
$data += $CustomObject;
$myJson = ConvertTo-Json -InputObject $data ;
Invoke-RestMethod -Uri http://localhost:9200/myindex/mytype/_bulk?pretty `
-Method POST -Body $myJson -ContentType "application/json"

批量請求不是實際的json。 您應該使用以下符號:

curl -XPOST 'localhost:9200/_bulk?pretty' -H 'Content-Type: application/json' -d'
{ "index" : { "_index" : "test", "_type" : "type1", "_id" : "1" } }
{ "field1" : "value1" }
{ "delete" : { "_index" : "test", "_type" : "type1", "_id" : "2" } }
{ "create" : { "_index" : "test", "_type" : "type1", "_id" : "3" } }
{ "field1" : "value3" }
{ "update" : {"_id" : "1", "_type" : "type1", "_index" : "test"} }
{ "doc" : {"field2" : "value2"} }
'
    $data = @()
    $CustomObject = [pscustomobject]@{
        SqlInstance    = "myserver1"
        Database       = "mydb"
        Schema         = "versioning"
        Name           = "DataVersionHistory"
        IndexSpaceUsed = 0
        DataSpaceUsed  = 0
        RowCount       = 0
    };
    $data += $CustomObject;
    $CustomObject = [pscustomobject]@{
        SqlInstance    = "myserver1"
        Database       = "mydb"
        Schema         = "versioning"
        Name           = "VersionHistory"
        IndexSpaceUsed = 10
        DataSpaceUsed  = 25
        RowCount       = 3000
    };
    $data += $CustomObject

至此,數組$data包含了一個對象集合。

注意:對於批量API,json數據的最后一行必須以換行符\\ n結尾。 因此,我使用here-string將換行符\\n附加到每個json元素。

還請注意,我刪除了漂亮的打印。 這是與批量api配合使用的好方法。

doc_as_upsert確保該文檔(如果存在)不加修改(如果未添加)。

$json_col = @()
$data | 
    ForEach-Object {
        #convert object to json
        $json_element = @{doc = $_; doc_as_upsert = $true}    
          | ConvertTo-Json -Depth 1 -Compress

        #construt here string with literal \n
        $json_col += @"

$json_element\n

"@
    }
Invoke-RestMethod -Method Post -Uri "http://localhost:9200/myindex/mytype/_bulk?" -Body $json_col  -ErrorAction Stop 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM