1、添加maven依赖
- <dependency>
- <groupId>org.elasticsearch</groupId>
- <artifactId>elasticsearch</artifactId>
- <version>0.90.0</version>
- </dependency>
建议使用maven管理项目,因为elasticsearch还有很多依赖包,手工维护很麻烦
2、创建连接elasticsearch服务的client
- 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));
3、创建索引
elasticsearch的java客户端,支持多种方式构建索引数据,这里有两种方式的代码示例:使用jsonbuilder构建数据
- 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());
另外一种,是把数据构造成json串,直接传给client
- 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());
实际应用中应该是下面一种更方便,可以把需要索引的对象直接扔过去了
4、根据id获取数据
- GetResponse responseGet = client.prepareGet("comment_index", "comment_ugc", "comment_123674").execute().actionGet();
- System.out.println(responseGet.getSourceAsString());
5、查询索引
- 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
6、删除索引,可以根据索引id删除索引,也可以构造query进行删除,这跟lucene的api是类似的,只不过api不一样而已
- DeleteResponse response = client.prepareDelete("comment_index", "comment_ugc", "comment_123674") .setOperationThreaded(false).execute().actionGet();
- System.out.println(response.getId());
这个删除有个小问题,如果删除完立即进行查询还是可以查到