IndexResponse response = client.prepareIndex(“twitter”, “tweet”)
.setSource(json)
.get();
3.3、使用第三方类库
import com.fasterxml.jackson.databind.*;
// instance a json mapper
ObjectMapper mapper = new ObjectMapper(); // create once, reuse
// generate json
byte[] json = mapper.writeValueAsBytes(yourbeaninstance);
IndexResponse response = client.prepareIndex(“twitter”, “tweet”)
.setSource(json, XContentType.JSON)
.get();
3.4、使用ElasticSearch自带类库
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();
4、Index API使用Demo
当前ElasticSearch为单机版。
package persistent.prestige.elasticsearchdemo;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
public class IndexApiDemo {
public static void main(String[] args) {
RestHighLevelClient client = EsClient.getClient();
try {
IndexRequest request = new IndexRequest();
request.index(“twitter”);
request.type("_doc");
request.id(“1”);
Map<String, String> source = new HashMap<>();
source.put(“user”, “dingw”);
source.put(“post_dat