Elasticsearch Java API

Elasticsearch之Java API


http://blog.csdn.net/gloria__zhang/article/details/49666301

Transport客户端

Settings settings = Settings.settingsBuilder()
                .put("client.transport.sniff", true)//这个客户端可以嗅到集群的其它部分,并将它们加入到机器列表。为了开启该功能,设置client.transport.sniff为true。
                .put("cluster.name", "video")
                .build();
Client client = TransportClient.builder()
                .settings(settings)
                .build()
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));

创建索引

构造JSON文档

elasticsearch要求开发者将需索引的内容以JSON的形式存储,我们可以通过四种方法进行JSON文档的生成:

  1. 利用byte[]或者String构造JSON文档

    String json = "{" +
        "\"user\":\"kimchy\"," +
        "\"postDate\":\"2013-01-30\"," +
        "\"message\":\"trying out Elasticsearch\"" +
    "}";
  2. 利用Map构造JSON文档

    Map json = new HashMap();
    json.put("user","kimchy");
    json.put("postDate",new Date());
    json.put("message","trying out Elasticsearch");
  3. 利用第三方库序列化对象,例如Jackson

    import com.fasterxml.jackson.databind.*;
    // instance a json mapper
    ObjectMapper mapper = new ObjectMapper(); // create once, reuse
    // generate json
    byte[] json = mapper.writeValueAsBytes(yourbeaninstance);
    // another method to generate json
    String json = builder.string();
  4. 利用elasticsearch内置提供的工具方法XContentFactory.jsonBuilder()生成JSON文档

    import static org.elasticsearch.common.xcontent.XContentFactory.*;
    XContentBuilder builder = jsonBuilder()
    .startObject()
        .field("user", "kimchy")
        .field("postDate", new Date())
        .field("message", "trying out Elasticsearch")
    .endObject()
    

创建索引

指定id

import static org.elasticsearch.common.xcontent.XContentFactory.*;
IndexResponse response = client.prepareIndex("twitter", "tweet", "1")
        .setSource(jsonBuilder()
                    .startObject()
                        .field("user", "kimchy")
                        .field("postDate", new Date())
                        .field("message", "trying out Elasticsearch")
                    .endObject()
                  )
        .get();

自动生成id

String json = "{" +
        "\"user\":\"kimchy\"," +
        "\"postDate\":\"2013-01-30\"," +
        "\"message\":\"trying out Elasticsearch\"" +
    "}";
IndexResponse response = client.prepareIndex("twitter", "tweet")
        .setSource(json)
        .get();
/*
*   IndexResponse对象会返回创建完成的索引信息
*/
// Index name
String _index = response.getIndex();
// Type name
String _type = response.getType();
// Document ID (generated or not)
String _id = response.getId();
// Version (if it's the first time you index this document, you will get: 1)
long _version = response.getVersion();
// isCreated() is true if the document is a new one, false if it has been updated
boolean created = response.isCreated();

从索引中获取数据

单条数据指定id查询

GetResponse response = client.prepareGet("twitter", "tweet", "1").get();

多条数据指定id查询

MultiGetResponse multiGetItemResponses = client.prepareMultiGet()
    .add("twitter", "tweet", "1")  //单id         
    .add("twitter", "tweet", "2", "3", "4")  //多个id 
    .add("another", "type", "foo")  // 也可以从其他索引进行查询       
    .get();

for (MultiGetItemResponse itemResponse : multiGetItemResponses) { 
    GetResponse response = itemResponse.getResponse();
    if (response.isExists()) {   //检查文档是否存在                   
        String json = response.getSourceAsString();  //访问_source字段 
    }
}

条件查询

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.index.query.QueryBuilders.*;
SearchResponse response = client.prepareSearch("index1", "index2")
        .setTypes("type1", "type2")
        .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
        .setQuery(QueryBuilders.termQuery("multi", "test"))                 // Query
        .setPostFilter(QueryBuilders.rangeQuery("age").from(12).to(18))     // Filter
        .setFrom(0).setSize(60).setExplain(true)
        .execute()
        .actionGet();

//以上的查询参数均为可选配置,不加参数则会搜索全部内容
SearchResponse response = client.prepareSearch().execute().actionGet();

注意

问题处理
检查引入的jar包中是否包含Jackson,将其去掉解决问题

信息: [Tess-One] loaded [], sites []
Exception in thread "main" java.lang.NoSuchFieldError: FAIL_ON_SYMBOL_HASH_OVERFLOW
    at org.elasticsearch.common.xcontent.smile.SmileXContent.(SmileXContent.java:50)
    at org.elasticsearch.common.xcontent.XContentFactory.contentBuilder(XContentFactory.java:124)
    at org.elasticsearch.action.support.ToXContentToBytes.buildAsBytes(ToXContentToBytes.java:62)
    at org.elasticsearch.action.search.SearchRequest.source(SearchRequest.java:250)
    at org.elasticsearch.action.search.SearchRequestBuilder.beforeExecute(SearchRequestBuilder.java:1012)
    at org.elasticsearch.action.search.SearchRequestBuilder.beforeExecute(SearchRequestBuilder.java:50)
    at org.elasticsearch.action.ActionRequestBuilder.execute(ActionRequestBuilder.java:85)
    at org.elasticsearch.action.ActionRequestBuilder.execute(ActionRequestBuilder.java:59)
    at org.gloria.index.SearchIndex.main(SearchIndex.java:38)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

删除索引

GetResponse response = client.prepareGet("twitter", "tweet", "1").get();

更新索引

  1. 利用UpdateRequest进行更新

    UpdateRequest updateRequest = new UpdateRequest();
    updateRequest.index("index");
    updateRequest.type("type");
    updateRequest.id("1");
    updateRequest.doc(jsonBuilder()
        .startObject()
            .field("gender", "male")
        .endObject());
    client.update(updateRequest).get();
  2. 通过Client中的prepareUpdate方法进行更新

     client.prepareUpdate("ttl", "doc", "1")
        .setDoc(jsonBuilder()               
            .startObject()
                .field("gender", "male")
            .endObject())
        .get();

你可能感兴趣的:(elasticsearch,学习笔记,Java)