分散検索Elasticsearch-インデックスの作成

2465 ワード

インデックスを作成する最初のステップは、インデックスを作成するオブジェクトをJson文字列に変換することです.
Jsonを生成する方法は多く、最も直接的なのは手書きで、あなたのエンティティをJsonに変換します.
String json = "{" +
        ""user":"kimchy"," +
        ""postDate":"2013-01-30"," +
        ""message":"trying out Elastic Search"," +
    "}";

2つ目は、Map方式を使用することです.
Map<String, Object> json = new HashMap<String, Object>();
json.put("user","kimchy");
json.put("postDate",new Date());
json.put("message","trying out Elastic Search");

3つ目は、Elasticを使うことです
searchが提供するヘルプクラス
import static org.elasticsearch.common.xcontent.XContentFactory.*;

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

4つ目はjacksonテクノロジーを使用してjacksonのjarパッケージをインポートし、mavenが管理するプロジェクトであればpomに直接
.xmlに追加:
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.1.3</version>
</dependency>

次に、
import com.fasterxml.jackson.databind.*;

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

// generate json
String json = mapper.writeValueAsString(yourbeaninstance);

次は
インデックスが作成されました:
IndexResponse response = client.prepareIndex("twitter", "tweet")
        .setSource(json)
        .execute()
        .actionGet();
        client.prepareIndexのパラメータは0個(その後index(String)メソッドとtype(String)メソッドを使用する必要がある)、2個(client)とすることができる.
.prepareIndex(index,type))と3つ(client.prepareIndex(index,type,id))のうち、indexはデータベース名に類似しており、typeはテーブル名に類似しており、idは各レコードの唯一の符号化であり、通常、エンティティの唯一の符号化を行う
ESのIDとして、もちろん、あげないときは、ESによって自動的に生成されます.
responseはElasticsearchがインデックスを作成した後、エンティティにフィードバックし、このエンティティから価値のある情報を得ることができます.
//     
String _index = response.index();
// type  
String _type = response.type();
//   ID
String _id = response.id();
//     
long _version = response.version();