spring data elastic search初识

首先pom文件里依赖:

		
		
			org.springframework.data
			spring-data-elasticsearch
			1.1.3.RELEASE
		
配置elastic

   

    

    
        
    

    

        
        
        
          
              cass
              
          
      

     


定义的文档结构:

@Document(indexName = "product-index",type = "PRODUCT",shards = 1, replicas = 1 ,refreshInterval = "-1")
public class ProductDocument {
    private
    @Id
    String id;
private  @Field(type = Nested)List bookCityCode;

}


Dao 

public interface ProductDocumentRepository extends ElasticsearchRepository {

    public ProductDocument findByProductId(long productId);
}

spring data会自动生成repository 的实现类。

也可以写查询的query:

结构bean:

@Data
@Builder
@Document(indexName = "conference-index", shards = 1, replicas = 0, indexStoreType = "memory", refreshInterval = "-1")
public class Conference {

	private @Id
	String id;
	private String name;
	private @Field(type = Date) String date;
	private @GeoPointField
	String location;
	private List keywords;

	private  List cityBeans;

	// do not remove it
	public Conference() {}

	// do not remove it - work around for lombok generated constructor for all params
	public Conference(String id, String name, String date, String location, List keywords,List cityBeans) {

		this.id = id;
		this.name = name;
		this.date = date;
		this.location = location;
		this.keywords = keywords;
		this.cityBeans=cityBeans;
	}
}

public class CityBean {
    private int code;
    private String name;
}

DAO :

public interface ConferenceRepository extends ElasticsearchRepository {

    @Query("{\"bool\":{\"must\":[{\"nested\":{\"path\":\"cityBeans\",\"query\":{\"bool\":{\"must\":[{\"match\":{\"cityBeans.code\":?0}}]}}}}]}}" )
    public List findByCityCode(int code,Pageable pageable);
}


 
  

t调用查询:

List conferences=repository.findByCityCode(1602,new PageRequest(0,20));

另外一种查询方式:

QueryBuilder builder = QueryBuilders.nestedQuery("cityBeans", QueryBuilders.boolQuery().must(termQuery("cityBeans.code", 1602)));
		QueryBuilder builder1=QueryBuilders.boolQuery().must(builder);
		Iterable result4 =repository.search(builder1);


你可能感兴趣的:(elastic)