elasticsearch java API

1、连接elasticseach
public class ElasticSearchComponent {

    TransportClient client = null;

    public ESClientSettings() {
        Settings settings = ImmutableSettings.settingsBuilder()
                .put("client.transport.sniff", true).build();
        client = new TransportClient(settings);
    }

    public void connect() {
        client.addTransportAddress(new InetSocketTransportAddress("localhost", 9300));
    }

    public void close(){
        client.close();
    }

}

2、创建索引
1.1、方法1
public void createIndex(){
try{
String json = "{\"title\":\"this\",\"description\":\"descript\",\"createDate\":new Date()}";
        IndexResponse response = client.prepareIndex("test_index", "test_type")
.setSource(json)
.execute()
.actionGet();
}catch (Exception e){
e.printStackTrace();
}
}

1.2、方法2
public void createIndex() {
try {
XContentBuilder doc = XContentFactory.jsonBuilder()
.startObject()
.field("title", "this")
.field("description", "descript")
.field("createDate", new Date())
.endObject();
client.prepareIndex("product_index", "product_type", "1").setSource(doc).execute().actionGet();
} catch (IOException e) {
e.printStackTrace();
}
}

 

3、查询(索引(数据库):animal_index,类型(表):cat_type)

3.1、根据ID进行单个查询
GetResponse response = client.prepareGet("animal_index", "cat_type", "1")
                .setOperationThreaded(false)
                .get();


3.2、分页查询所有记录
QueryBuilder qb=new MatchAllQueryBuilder();
SearchResponse response= client.prepareSearch("animal_index").setTypes("cat_type").setQuery(qb).setFrom(0)
.setSize(100).get();
SearchHits searchHits = response.getHits();
for(SearchHit hit:searchHits.getHits()){
logger.log(Level.INFO , hit.getSourceAsString());
}
相当于查询关系型数据库:sql select * from animal_index.cat_type limit 100;


3.3、根据多条件组合与查询
QueryBuilder qb=QueryBuilders.boolQuery().must(QueryBuilders.termQuery("skin","yellow")).must(QueryBuilders.termQuery("age",2)) ;
SearchRequestBuilder sv=client.prepareSearch("animal_index").setTypes("cat_type").setQuery(qb).setFrom(0)
.setSize(100);
logger.log(Level.INFO,sv.toString());
SearchResponse response= sv.get();
SearchHits searchHits = response.getHits();
for(SearchHit hit:searchHits.getHits()){
logger.log(Level.INFO , hit.getSourceAsString());
}
相当于查询关系型数据库:select * from animal_index.cat_type where skin='yellow' and age=2


3.4、多条件或查询
QueryBuilder qb=QueryBuilders.termQuery("user","tom-1");
QueryBuilder qb1=QueryBuilders.termQuery("user","tom-2");
SortBuilder sortBuilder=SortBuilders.fieldSort("age");
sortBuilder.order(SortOrder.DESC);
QueryBuilder s=QueryBuilders.boolQuery().should(qb).should(qb1);//.must(qb5);
SearchRequestBuilder sv=client.prepareSearch("animal_index").setTypes("cat_type").setQuery(s).addSort(sortBuilder).setFrom(0)
.setSize(100);
logger.log(Level.INFO,sv.toString());
SearchResponse response= sv.get();
SearchHits searchHits = response.getHits();
for(SearchHit hit:searchHits.getHits()){
logger.log(Level.INFO , hit.getSourceAsString());
}
相当于查询关系型数据库:select * from animal_index.cat_type where user='tom-1' or  user='tom-2';


3.5、范围查询 
// RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("age").from(30,true).to(30,true);
// RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("age").gt(30 );
RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("age").gte(30 );
QueryBuilder s=QueryBuilders.boolQuery().must(rangeQueryBuilder);//.must(qb5);
SearchRequestBuilder sv=client.prepareSearch("animal_index").setTypes("cat_type").setQuery(s).setFrom(0)
.setSize(100);
logger.log(Level.INFO,sv.toString());
SearchResponse response= sv.get();
SearchHits searchHits = response.getHits();
for(SearchHit hit:searchHits.getHits()){
logger.log(Level.INFO , hit.getSourceAsString());
}
相当于查询关系型数据库;select * from animal_index.cat_type where age >=30 and age<=30;


3.6、包含查询
List<String> strs=new ArrayList<>();
strs.add("tom-1");
strs.add("tom-2");
strs.add("tom-3");
QueryBuilder qb=QueryBuilders.termsQuery("user",strs);
SearchRequestBuilder sv=client.prepareSearch("animal_index").setTypes("cat_type").setQuery(qb).setFetchSource("age",null).setFrom(0)
.setSize(100);
logger.log(Level.INFO,sv.toString());
SearchResponse response= sv.get();
SearchHits searchHits = response.getHits();
for(SearchHit hit:searchHits.getHits()){
logger.log(Level.INFO , hit.getSourceAsString());
}
相当于查询关系型数据库;select age from animal_index.cat_type where user in ('tom-1','tom-2','tom-3');


3.7、专门按id进行的包含查询
QueryBuilder qb=QueryBuilders.idsQuery(1+"");
SearchRequestBuilder sv=client.prepareSearch("animal_index").setTypes("cat_type").setQuery(qb).setFetchSource("age",null).setFrom(0)
.setSize(100);
logger.log(Level.INFO,sv.toString());
SearchResponse response= sv.get();
SearchHits searchHits = response.getHits(); 
for(SearchHit hit:searchHits.getHits()){
logger.log(Level.INFO , hit.getSourceAsString());
}
相当于查询关系型数据库;select age from animal_index.cat_type where id in ('1');


3.8、按通配符查询
QueryBuilder qb = QueryBuilders.wildcardQuery("user", "t*m*");
//Fuzziness fuzziness=Fuzziness.fromEdits(2);
//QueryBuilder qb = QueryBuilders.fuzzyQuery("user","om").fuzziness(fuzziness);
//QueryBuilder qb = QueryBuilders.prefixQuery("user", "tom-2");
SearchRequestBuilder sv=client.prepareSearch("animal_index").setTypes("cat_type").setQuery(qb).setFetchSource("user",null).setFrom(0)
.setSize(100);
logger.log(Level.INFO,sv.toString());
SearchResponse response= sv.get();
SearchHits searchHits = response.getHits();
for(SearchHit hit:searchHits.getHits()){
logger.log(Level.INFO , hit.getSourceAsString());
}
通配符查询像我们sql里的like

3.8、match_parse查询
3.8.1、match_parse查询相当于结构化数据库模糊查询like 。
例子: "我是中学生" 伪代码match_parse("一个") 会对查询字符串分词[一,个]。同时需要有"一个"才会被搜索出来


3.8.2、match_parse与match区别
match查询只有包含"一"或者"个"或者"一个"都会被搜索出来。这是与match_parse比较大区别

 

 

4、修改

4.1、传入json字符串更新
public void testUpdate() { JSONObject json = new JSONObject(); json.put("name", "李四"); json.put("age", "20"); json.put("sex", "男"); json.put("grade", "高二"); UpdateResponse response = client.prepareUpdate("stu_index", "stu_type", "id_000001").setDoc(json.toJSONString(), XContentType.JSON).get(); }

 

5、删除索引数据

5.1、根据条件删除
public void delbyquery(){ QueryBuilder query = QueryBuilders.fieldQuery("type", "1"); client.prepareDeleteByQuery("productindex").setQuery(query).execute().actionGet(); }
5.2、根据ID删除 public void delbyid(){ DeleteResponse response = client.prepareDelete("productindex", "productindex", "1") .execute() .actionGet(); }

 

posted @ 2019-12-13 16:21  N神3  阅读(1506)  评论(0编辑  收藏  举报