elasticsearch java 增刪改查 版本1

來源:互聯網
上載者:User

既然是開發篇,主要以代碼為主,輔助一些說明。所有的內容都是代碼實際應該驗證過的。

引入的標頭檔:

import static org.elasticsearch.node.NodeBuilder.nodeBuilder; import java.io.IOException;import java.net.InetAddress;import java.util.Date;import java.util.Map;import java.util.Set; import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;import org.elasticsearch.action.admin.indices.create.CreateIndexRequestBuilder;import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;import org.elasticsearch.action.index.IndexResponse;import org.elasticsearch.client.Client;import org.elasticsearch.client.ClusterAdminClient;import org.elasticsearch.client.transport.TransportClient;import org.elasticsearch.cluster.health.ClusterIndexHealth;import org.elasticsearch.common.settings.Settings;import org.elasticsearch.common.transport.InetSocketTransportAddress;import org.elasticsearch.common.xcontent.XContentBuilder;import org.elasticsearch.common.xcontent.XContentFactory;import org.elasticsearch.node.Node;import static org.elasticsearch.common.xcontent.XContentFactory.*;


建立索引

XContentBuilder mapping = XContentFactory.jsonBuilder()    .startObject()        .startObject("settings")          .field("number_of_shards", 1)//設定分區數量          .field("number_of_replicas", 0)//設定副本數量        .endObject()    .endObject()    .startObject()        .startObject(type)//type名稱            .startObject("properties") //下面是設定文檔列屬性。               .startObject("type").field("type", "string").field("store", "yes").endObject()               .startObject("eventCount").field("type", "long").field("store", "yes").endObject()               .startObject("eventDate").field("type", "date").field("format", "dateOptionalTime").field("store", "yes").endObject()               .startObject("message").field("type", "string").field("index", "not_analyzed").field("store", "yes").endObject()            .endObject()        .endObject()    .endObject();                        CreateIndexRequestBuilder cirb = client        .admin()        .indices()        .prepareCreate(indexName)//index名稱        .setSource(mapping); CreateIndexResponse response = cirb.execute().actionGet();if (response.isAcknowledged()) {    System.out.println("Index created.");} else {    System.err.println("Index creation failed.");}


增加文檔

IndexResponse response = client        .prepareIndex(indexName, type, "1")        .setSource(//這裡可以直接用json字串                jsonBuilder().startObject()                    .field("type", "syslog")                    .field("eventCount", 1)                    .field("eventDate", new Date())                    .field("message", "secilog insert doc test")                .endObject()).get();System.out.println("index:"+response.getIndex()        +" insert doc id:"+response.getId()        +" result:"+response.isCreated());


查詢文檔

GetResponse response = client.prepareGet("secilog", "log", "1").get();String source = response.getSource().toString();long version = response.getVersion();String indexName = response.getIndex();String type = response.getType();String id = response.getId();


修改文檔

修改文檔有兩種方式,一種是直接修改,另一種是如果文檔不存在則插入存在則修改。

第一種代碼

UpdateRequest updateRequest = new UpdateRequest();updateRequest.index(indexName);updateRequest.type(type);updateRequest.id("1");updateRequest.doc(jsonBuilder()        .startObject()            .field("type", "file")        .endObject());client.update(updateRequest).get();


第二種代碼:

IndexRequest indexRequest = new IndexRequest(indexName, type, "3").source(jsonBuilder()    .startObject()        .field("type", "syslog")        .field("eventCount", 2)        .field("eventDate", new Date())        .field("message", "secilog insert doc test")    .endObject());UpdateRequest updateRequest = new UpdateRequest(indexName, type, "3")    .doc(jsonBuilder()        .startObject()            .field("type", "file")        .endObject())    .upsert(indexRequest);              client.update(updateRequest).get();


刪除文檔

DeleteResponse dresponse = client.prepareDelete("secilog", "log", "4").get();boolean isFound = dresponse.isFound(); //文檔存在返回true,不存在返回false;


刪除索引

DeleteIndexRequest delete = new DeleteIndexRequest("secilog");client.admin().indices().delete(delete);


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.