我想使用 java 将 json 文件发送到 elasticsearch

I want to send json file to elasticsearch using java

我想使用 java httprequest 调用 elasticsearch 的 _bulk api 将数据发送到 ElasticSearch

参考:https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html

这给了我这个错误

"Response: HttpResponseProxy{HTTP/1.1 406 Not Acceptable [content-type: application/json; charset=UTF-8] org.apache.http.client.entity.DecompressingEntity@3532ec19}"

下面是我的Java代码:

package com.ElasticPublisher;

import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.FileEntity;
import org.apache.http.impl.client.HttpClientBuilder;
public class ElasticPublisher {
    public static void main(String args[]){
        try {
            sendFile();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    private static void sendFile() throws Exception{
        String fileName = "C:\Users\malin\Documents\ELK\employee.json";
        File jsonFile = new File(fileName);
        HttpEntity  entity = new FileEntity(jsonFile);
        HttpPost post = new HttpPost("http://localhost:9200/_bulk");
        post.setEntity(entity);
        HttpClientBuilder clientBuilder = HttpClientBuilder.create();
        HttpClient client = clientBuilder.build();
        post.addHeader("content-type", "text/plain");
        post.addHeader("Accept","text/plain");
        HttpResponse response = client.execute(post);
        System.out.println("Response: " + response);
    }
}

*

您的问题很可能与您设置的 Content-Type header 有关。

Starting from Elasticsearch 6.0, all REST requests that include a body must also provide the correct content-type for that body.

在 v6.0 之前,Elasticsearch 过去常常猜测您在内容中的意思。更准确地说,如果您的 body 以 “{” 开头,那么 Elasticsearch 会猜测您的内容实际上是 JSON。但是,这种方法存在问题,有时会导致意外的解析错误。因此,他们得出的结论是"being explicit is the safer, clearer and more consistent approach".

总而言之,您还没有分享实体文件的内容(employee.json)。简而言之,考虑到实体内容,您需要确保 Content-Type 有效。如果您要发送与 text/plain 不同的内容(例如 json),您必须考虑将 Content-Type header 替换为以下内容:

post.addHeader("Content-Type", "application/json");