【问题标题】:Elasticsearch Java API Index DocumentElasticsearch Java API 索引文档
【发布时间】:2013-11-07 20:23:24
【问题描述】:
  1. 下载 .90.6,解压,将 Elastic Search 移至 /usr/share/elasticsearch(在 centosx64 6.4 上具有 chmod 777 -R 权限),将集群重命名为 somethingstupid 并启动服务器。

  2. 已安装插件 ESHead 和 ESBrowser b/c 我是新的并且需要它(我习惯了 Solr 的漂亮 ui)。这样我就知道服务器也在运行。

  3. 我可以通过 curl 创建索引:curl -XPOST 'http://localhost:9200/testindex' 并删除它:curl -XDELETE 'http://localhost:9200/testindex'

当我尝试创建新索引并为 article 类型的文档建立索引并通过 Java API 查看它时,eclipse 运行代码,在控制台中显示基本日志记录,然后关闭且没有错误。此外,在我的日志中,最新的一行只是显示我已经启动了弹性搜索,但没有别的。就像代码甚至没有达到弹性搜索一样。运行 java api 后没有显示索引或文章。我错过了什么?

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.elasticsearch.client.Client;
import org.elasticsearch.node.Node;

import static org.elasticsearch.node.NodeBuilder.*;

public class PostES {

    public static void main (String args[]){
        PostES p = new PostES();
        p.postElasticSearch();
    }


    public static Map<String, Object> putJsonDocument(String title, String content, Date postDate, String author){

            Map<String, Object> jsonDocument = new HashMap<String, Object>();

            jsonDocument.put("title", title);
            jsonDocument.put("conten", content);
            jsonDocument.put("postDate", postDate);
            jsonDocument.put("author", author);

            return jsonDocument;
    }


    private void postElasticSearch(){

            Node node    = nodeBuilder().node();
            Client client   = node.client();

            client.prepareIndex("testindex", "article")
                      .setSource(putJsonDocument("Example Title",
                                                 "This description is so important. You don't even know!",
                                                 new Date(),
                                                 "J.R."))
                                                 .execute().actionGet();

            node.close();
        }


}

我的来源:http://java.dzone.com/articles/elasticsearch-java-api。包括弹性文档在内的所有其他内容都以某种方式失败了......(方法 jsonBuilder() 对于 PostES 类型未定义)。

根据文档,我应该能够做到这一点。但它也无能为力:

import static org.elasticsearch.node.NodeBuilder.nodeBuilder;

import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.node.Node;


public class TestPostMethod2 {

    public static void main(String[] args) {
        Node node = nodeBuilder().local(true).node();
        Client client = node.client();

            String json = 
                    "{\"user\":\"kimchy\"," +
                    "\"postDate\":\"2013-01-30\"," +
                    "\"message\":\"trying out Elastic Search\"}";              

            IndexResponse response = client.prepareIndex("testindex", "article")
                    .setSource(json)
                    .execute()
                    .actionGet();
    }

}

【问题讨论】:

    标签: elasticsearch


    【解决方案1】:

    创建节点时需要指定集群名称,指定为client node,或者使用transport client。

    您当前在这两种情况下所做的是启动一个新节点,该节点创建一个具有默认名称的新集群,而您希望有一个客户端节点加入您现有的集群。

    Node node = nodeBuilder().clusterName("somethingstupid").client(true).node();
    

    【讨论】:

      【解决方案2】:

      不确定这是否相关,但最初我试图从 eclipse 连接到运行中的 ES 集群时,我不得不将它添加到我的 tomcat 的参数中:

      -Delasticsearch -Des.path.home=/usr/local/opt/elasticsearch
      

      其中 elasticsearch 是您在 elasticsearch.yml 中定义的名称,当然还有您安装 ES 的路径

      【讨论】:

      • Tomcat?我应该在容器内粘贴弹性搜索?伙计,我很困惑。为什么人们说这很容易上手?我一定是个真正的白痴……
      • 呸没关系,我的错。 Node node = nodeBuilder().clusterName("somethingstupid").node(); Client client = node.client(); 如果集群名称不同,则需要在连接时指定集群名称
      【解决方案3】:

      让 api 工作的一种方法是不使用它:

      import java.io.BufferedReader;
      import java.io.InputStreamReader;
      import org.apache.http.HttpResponse;
      import org.apache.http.client.methods.HttpPost;
      import org.apache.http.entity.StringEntity;
      import org.apache.http.impl.client.DefaultHttpClient;
      
      
      public class PostHttpClient {
      
          public static void main(String[] args) {
              try{
              DefaultHttpClient httpClient = new DefaultHttpClient();
              HttpPost postRequest = new HttpPost(
                  "http://localhost:9200/testindex/article");
      
              StringEntity input = new StringEntity("{\"name\":\"ES JAVA API WorkAround\",\"category\":\"Garbage\"}");
              input.setContentType("application/json");
              postRequest.setEntity(input);
      
              HttpResponse response = httpClient.execute(postRequest);
      
              if (response.getStatusLine().getStatusCode() != 201) {
                  throw new RuntimeException("Failed : HTTP error code : "
                      + response.getStatusLine().getStatusCode());
              }
      
              BufferedReader br = new BufferedReader(
                              new InputStreamReader((response.getEntity().getContent())));
      
              String output;
              System.out.println("Output from Server .... \n");
              while ((output = br.readLine()) != null) {
                  System.out.println(output);
              }
      
              httpClient.getConnectionManager().shutdown();
      
            } catch (Exception e) {
      
              e.printStackTrace();
      
            } 
      
          }
      
      }
      

      【讨论】:

        【解决方案4】:

        为什么不使用带有 java.util.Map 的传输客户端?

        import org.elasticsearch.action.index.IndexResponse;
        import org.elasticsearch.client.Client;
        import org.elasticsearch.client.transport.TransportClient;
        import org.elasticsearch.common.transport.InetSocketTransportAddress;
        
        import java.util.*;
        
        public class Test {
        
            public static Client getTransportClient(String host, int port) {
        
                return new TransportClient()
                        .addTransportAddress(new InetSocketTransportAddress(host, port));
            }
        
            public static IndexResponse doIndex(Client client, String index, String type, String id, Map<String, Object> data) {
        
                return client.prepareIndex(index, type, id)
                        .setSource(data)
                        .execute()
                        .actionGet();
            }
        
            public static void main(String[] args) {
        
                Client client = getTransportClient("localhost", 9300);
        
                String index  = "twitter";
                String type   = "tweet";
                String id     = null;        // set id here if you want to
        
                Map<String, Object> data = new HashMap<String, Object>();
                data.put("text", "Posted from Java @ " + System.currentTimeMillis());
                data.put("user", "Igal");
                data.put("date", new Date());
        
                IndexResponse result = doIndex(client, index, type, id, data);
        
                System.out.println((result.isCreated() ? "created" : "updated") + " document " + result.getId() );
        
                client.close();
            }
        }
        

        【讨论】:

          【解决方案5】:

          我建议任何人使用rest client(jest)而不是传输客户端,记得添加link-1和link-2中指定的所有依赖项

          替换 "index_name" = 带有您的索引名称

          使用java创建简单的索引和插入数据,

          public void setData(String data)
          {           
              try
          
              {
               // Construct a new Jest client according to configuration via factory
               JestClientFactory factory = new JestClientFactory();
               factory.setHttpClientConfig(new HttpClientConfig
                                      .Builder("http://localhost:9200")
                                      .multiThreaded(true)
                                      .build());
               JestClient client = factory.getObject();
          
          client.execute(new CreateIndex.Builder("index_name").build());
          
          
          
                  String source = jsonBuilder()
                          .startObject()
                          .field("data", data)
                           //other data
                          .endObject().string();
                  System.out.println(source); // verify data
          
                  Index index = new Index.Builder(source).index("index_name").type("_type").build();
                  client.execute(index);
          
          
              }
              catch(IOException i)
              {
                  i.printStackTrace();
              }
              catch(Exception e)
              {
                  e.printStackTrace();
              }
           }
          

          【讨论】:

            猜你喜欢
            • 2019-01-22
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-08-14
            • 2015-09-05
            • 1970-01-01
            • 2018-08-25
            • 2017-07-04
            相关资源
            最近更新 更多