gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 02:05:22 24 4
gpt4 key购买 nike

我想使用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 过去常常猜测您在内容中的含义。更准确地说,如果您的正文以 “{” 开头,那么 Elasticsearch 会猜测您的内容实际上是 JSON。然而,这种方法是有问题的,有时会导致意外的解析错误。因此,他们得出了“明确是更安全、更清晰、更一致的方法”的结论。

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

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

关于java - 我想使用java将json文件发送到elasticsearch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50890487/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com