1. 程式人生 > >ElasticSearch(二)--索引API

ElasticSearch(二)--索引API

對於es的一些基本概念還不是很清楚的同學可以移步,es概念

在es中,允許將型別化的JSON文件編入特定的索引並使其可搜尋。並且提供了一下四種的實現方式來生成這樣json格式。

es中json的生成方式:

1. 手動編寫json

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

2. 通過map

Map<String, Object> json = new HashMap<String, Object>();
json.put("user","kimchy");
json.put("postDate",new Date());
json.put("message","trying out Elasticsearch");

3. 通過第三方庫,如gson,jackson等,

jackson

import com.fasterxml.jackson.databind.*;

// instance a json mapper
ObjectMapper mapper = new ObjectMapper(); // create once, reuse

// generate json
byte[] json = mapper.writeValueAsBytes(yourbeaninstance);

Gson

JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("name", "java程式設計思想");
jsonObject.addProperty("publicdate", "2018-05-09");
jsonObject.addProperty("price", "100");
String json = jsonObject.toString();

4. es中提供的XContentFactory.jsonBuilder()

import static org.elasticsearch.common.xcontent.XContentFactory.*;

XContentBuilder builder = XContentFactory.jsonBuilder()
    .startObject()
        .field("user", "kimchy")
        .field("postDate", new Date())
        .field("message", "trying out Elasticsearch")
   .endObject();   String json = builder.string();

XContentBuileder除了能夠自己手動新增屬性外,還能夠將map直接轉換成json。

Map<String, Object> map = new HashMap<String, Object>();
map.put("user","kimchy");
map.put("postDate",new Date());
map.put("message","trying out Elasticsearch");
XContentBuilder object = XContentFactory.jsonBuilder()
					.map(map);
String json = object.string();

ES索引的API

操作es都是通過TransportClient物件來操作的,

獲取TransportClient物件的api

private static String address = "192.168.17.137";
private static int port = 9300;
private static TransportClient client = null;
client  = new PreBuiltTransportClient(Settings.EMPTY) // 如果是叢集版 配置需要進行修改
					.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(address), port));

1. 建立索引:

IndexResponse response = client.prepareIndex("twitter", "tweet", "1") 
		        .setSource(json) // 型別可以為MAP 集合,Byte陣列,json 字串,但如果是JSON字串的話,需要在後面加一個引數XContentType.JSON
		        .get();

prepareIndex有三個方法,如下

IndexRequestBuilder requestBuilder = client.prepareIndex();
IndexRequestBuilder requestBuilder = client.prepareIndex(index, type); // 指定索引名稱,與索引下的型別
IndexRequestBuilder requestBuilder = client.prepareIndex(index, type, id); //指定索引名稱,索引下的型別,以及id

此外,值得一提的是,setSource方法,有多個重構方法,可以使用多種不同的型別,如map,byte陣列等多種,具體可以檢視api。建立索引後,可以通過返回的resonse物件,獲取狀態資訊:

System.out.println("索引名稱"+response.getIndex());
System.out.println("索引型別"+response.getType());
System.out.println("結果"+response.getResult());
System.out.println("id"+response.getId());
System.out.println("狀態"+response.status());

2. 修改索引:

    修改索引,主要是通過id獲取到索引,在對索引進行修改。

JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("name", "java非常牛");
jsonObject.addProperty("publicdate", "2018-05-09");
jsonObject.addProperty("price", "101");
UpdateResponse response = client.prepareUpdate("book", "java","1")
				.setDoc(jsonObject.toString(),XContentType.JSON)
				.get();

還有另外一種寫法,其實與上面的實現基本一致。

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();

3. 獲取索引,通過id獲取索引,主要是通過prepareGet方法,根據id來獲取。

GetResponse response = client.prepareGet("book", "java","1").get();
		System.out.println(response.getSourceAsString());

關於文件的搜尋,後面在做詳解。

4. 刪除索引

DeleteResponse response = client.prepareDelete("book", "java","1").get();

另外一種方式,根據查詢刪除對應的資料

BulkByScrollResponse response =
    DeleteByQueryAction.INSTANCE.newRequestBuilder(client)
        .filter(QueryBuilders.matchQuery("gender", "male")) 
        .source("persons")                                  
        .get();                                             
long deleted = response.getDeleted();  

以上就是關於索引的基本操作了