代码之家  ›  专栏  ›  技术社区  ›  nehacharya

如何使用Spring数据从elasticsearch读取文档?

  •  0
  • nehacharya  · 技术社区  · 7 年前

    我创建了一个包含20个文档的“公寓”类型的索引(house)。我使用postman将Json作为二进制文件上传到elasticsearch中。我有一个Spring Boot项目,它包含以下类:

    1. -我已经配置了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()); 
        }
      }
      
    2. 公寓.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
      }
      
    3. -这是一个扩展ElasticsearchRepository接口以执行crud操作的接口。

      public interface ApartmentSearchRepository extends ElasticsearchRepository<Apartments, String> {
      List<Apartments> findByApartmentName(String apartmentName);
      }
      
    4. EsApartmentService.java文件 -

      @Service
      public class EsApartmentService {
      
      @Autowired
      ApartmentSearchRepository apartmentSearchRepository;
      
      public List<Apartments> getApartmentByName(String apartmentName) {
          return apartmentSearchRepository.findByApartmentName(apartmentName);
         }
      }
      
    5. -我已经创建了一个端点,可以返回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读取这些文档。我经历了几个解决方案,但大多数都是从代码本身设置文档数据。

    我无法通过点击我在控制器中指定的端点来检索这些文档。有人能告诉我我错过了什么吗?谢谢!:)

    编辑: enter image description here

    2 回复  |  直到 7 年前
        1
  •  2
  •   ibexit    7 年前

    据我所知,您可以使用@JsonProperty将POJO映射到查询响应,但是您正在失去使用spring数据的动态finder方法(findBy*)的能力。spring数据的动态finders生成依赖于反射,因此POJO中的字段名变得非常重要。

    您介意更改POJO或文档中的字段名来验证这一点吗?或者只是定义一个自定义查询?还有一个功能强大的java api,您可以在其中定义更复杂的查询: https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#elasticsearch.misc.filter

        2
  •  0
  •   nehacharya    7 年前

    1. 公寓.java -已删除@JsonProperty

      @Document(indexName = "house", type = "apartments")
      //@JsonIgnoreProperties(ignoreUnknown=true)
      public class Apartments {
      
       @Id
       private String id;
      
       //@JsonProperty("apartment_ID")
       private String apartment_ID;
      
       //@JsonProperty("Area_Name")
       private String area_Name;
      
       //@JsonProperty("Apartment_Name")
       private String apartment_Name;
      }
      
    2. -

      @Service
      public class EsApartmentService {
      @Autowired
      private  ElasticsearchTemplate elasticsearchTemplate; 
      
      public List<Apartments> getApartmentByName(String apartmentName) {
         SearchQuery searchQuery = new NativeSearchQueryBuilder()           
        .withQuery(org.elasticsearch.index.query.QueryBuilders
          .matchQuery("apartment_Name", apartmentName)).build();
      Page<Apartments> sampleEntities = 
          elasticsearchTemplate.queryForPage(searchQuery,Apartments.class);      
      return sampleEntities.getContent();
        }
      }
      
    3. ApartmentSearchRepository.java文件

    推荐文章