我创建了一个包含20个文档的“公寓”类型的索引(house)。我使用postman将Json作为二进制文件上传到elasticsearch中。我有一个Spring Boot项目,它包含以下类:
-
-我已经配置了clustername,它是application.properties文件中的默认名称。
@Configuration
@EnableElasticsearchRepositories(basePackages = "com.search.repository")
public class EsConfig {
@Value("${elasticsearch.clustername}")
private String EsClusterName;
@Bean
public Client esClient() throws UnknownHostException {
Settings esSettings = Settings.builder()
.put("cluster.name", EsClusterName)
.put("client.transport.sniff", true)
.put("client.transport.ignore_cluster_name", false)
.build();
TransportClient client = new PreBuiltTransportClient(esSettings)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));
return client;
}
@Bean
public ElasticsearchOperations elasticsearchTemplate() throws Exception{
return new ElasticsearchTemplate(esClient());
}
}
-
公寓.java
-这是我的数据模型。这些文档在elasticsearch中有以下字段。
@Document(indexName = "house", type = "apartments")
@JsonIgnoreProperties(ignoreUnknown=true)
public class Apartments {
@Id
private String id;
@JsonProperty("Apartment_Name")
private String apartmentName;
@JsonProperty("Apartment_ID")
private String apartmentId;
@JsonProperty("Area_Name")
private String areaName;
//constructors along with getters and setters
}
-
-这是一个扩展ElasticsearchRepository接口以执行crud操作的接口。
public interface ApartmentSearchRepository extends ElasticsearchRepository<Apartments, String> {
List<Apartments> findByApartmentName(String apartmentName);
}
-
EsApartmentService.java文件
-
@Service
public class EsApartmentService {
@Autowired
ApartmentSearchRepository apartmentSearchRepository;
public List<Apartments> getApartmentByName(String apartmentName) {
return apartmentSearchRepository.findByApartmentName(apartmentName);
}
}
-
-我已经创建了一个端点,可以返回elasticsearch中的20个文档(另外,在我的项目中,公寓是一个POJO,公寓是数据模型。)
@Autowired
EsApartmentService esApartmentService;
@GetMapping(path = "/search",produces = "application/json")
public Set<Apartment> searchApartmentByName(
@RequestParam(value = "apartmentName", defaultValue = "") String apartmentName) throws IOException {
List<Apartment> apartments= new ArrayList<>();
esApartmentService.getApartmentByName(apartmentName).forEach(apartment-> {
apartments.add(new Apartment(apartment.getApartmentName(), apartment.getApartmentId(), apartment.getAreaName()));
});
return apartments.stream()
.collect(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Apartment::getApartmentId))));
}
此代码返回状态200,但响应为空。我试过调试,但似乎无法从elasticsearch读取这些文档。我经历了几个解决方案,但大多数都是从代码本身设置文档数据。
我无法通过点击我在控制器中指定的端点来检索这些文档。有人能告诉我我错过了什么吗?谢谢!:)
编辑: