人.java
@Document(indexName = "person", type = "user")
public class Person {
@Id
private String id;
@Field(type = FieldType.String)
private String name;
@Field(type = FieldType.Nested)
private List<Car> cars;
// getter/setter
}
汽车.java
public class Car {
@Field(type = FieldType.String)
private String name;
@Field(type = FieldType.String)
private String model;
// getter/setter
}
使用 main 方法进行索引和搜索
public class SpringElasticSearchTest {
public static void main(String[] args) {
ApplicationContext applicationContext = new FileSystemXmlApplicationContext(
"src/main/webapp/WEB-INF/spring/applicationContext.xml");
ElasticsearchTemplate est = (ElasticsearchTemplate) applicationContext
.getBean("elasticsearchTemplate");
Person pers = new Person();
pers.setName("Manish");
pers.setId("1");
List<Car> cars = new ArrayList<Car>();
Car subaru = new Car();
subaru.setName("Tata");
subaru.setModel("Safari");
cars.add(subaru);
pers.setCars(cars);
IndexQuery indexQuery = new IndexQuery();
indexQuery.setId(pers.getId());
indexQuery.setObject(pers);
est.deleteIndex("person");
est.createIndex(Person.class);
est.putMapping(Person.class);
est.index(indexQuery);
est.refresh(Person.class, true);
QueryBuilder builder = nestedQuery(
"cars",
boolQuery().must(termQuery("cars.name", "Tata")).must(
termQuery("cars.model", "Safari")));
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(
builder).build();
List<Person> persons = est.queryForList(searchQuery, Person.class);
System.out.println("Person List : " + persons);
}
索引工作正常,但搜索功能不起作用。
我得到以下输出:
人员名单:[]
请建议。提前致谢。