使用java访问elasticsearch创建索引
1、添加maven依赖
<dependency><groupId>org.elasticsearch</groupId><artifactId>elasticsearch</artifactId><version>0.90.0</version></dependency>
Settings settings = ImmutableSettings.settingsBuilder().put("client.transport.sniff", true).put("cluster.name", "name of node").build();Client client = new TransportClient(settings).addTransportAddress(new InetSocketTransportAddress("ip of server", 9300));
IndexResponse response = client.prepareIndex("comment_index", "comment_ugc", "comment_123674") .setSource( XContentFactory.jsonBuilder() .startObject() .field("author", "569874") .field("author_name", "riching") .field("mark", 232) .field("body", "北京不错,但是人太多了") .field("createDate", "20130801175520") .field("valid", true) .endObject()) .setTTL(8000) .execute().actionGet();System.out.println(response.getId());
Student student = new Student(103161066, 20, "riching", "beijing");String jsonValue = mapper.writeValueAsString(student);response = client.prepareIndex("student_index", "student_info", "stu_103161066").setSource(jsonValue).execute().actionGet();System.out.println(response.getId());
GetResponse responseGet = client.prepareGet("comment_index", "comment_ugc", "comment_123674").execute().actionGet();System.out.println(responseGet.getSourceAsString());
SearchRequestBuilder builder = client.prepareSearch("comment_index").setTypes("comment_ugc").setSearchType(SearchType.DEFAULT).setFrom(0).setSize(100);BoolQueryBuilder qb = QueryBuilders.boolQuery().must(new QueryStringQueryBuilder("北京").field("body")) .should(new QueryStringQueryBuilder("太多").field("body"));builder.setQuery(qb);SearchResponse response = builder.execute().actionGet();System.out.println(" " + response);System.out.println(response.getHits().getTotalHits());
{ "took" : 8, "timed_out" : false, "_shards" : { "total" : 5, "successful" : 5, "failed" : 0 }, "hits" : { "total" : 1, "max_score" : 0.19178301, "hits" : [ { "_index" : "comment_index", "_type" : "comment_ugc", "_id" : "comment_123674", "_score" : 0.19178301, "_source" : {"author":"569874","author_name":"riching","mark":232,"body":"北京不错,但是人太多了","createDate":"20130801175520","valid":true} } ] }}1
DeleteResponse response = client.prepareDelete("comment_index", "comment_ugc", "comment_123674") .setOperationThreaded(false).execute().actionGet();System.out.println(response.getId());