首页 > 解决方案 > 根据单个字段的值从 ElasticSearch 文档中返回值

问题描述

我正在尝试使用应用程序从Elasticsearch 文档中返回值。这是我的搜索代码SpringBootJAVA

//1
 SearchResponse response = client.prepareSearch("recipe1")
            .addDocValueField("Title")
            .setSize(10)
            .get();
//2
 SearchResponse scrollResp = client.prepareSearch()
            .setIndices("recipe1")
            .setTypes("default")
            .setSearchType(SearchType.QUERY_AND_FETCH)
            .setFetchSource(new String[]{"Title"}, null)
    .setQuery(QueryBuilders.matchAllQuery())
            .setSize(10).execute().actionGet();

我的文档中有多个字段,但我想返回Title字段与传递给Elasticsearch.

我也使用了这段代码,但没有得到确切的输出。而在某些情况下(我已经尝试了很多)它返回所有值,无论是否与搜索的标题匹配。我是新手Elasticsearch。我知道我把查询弄错了,但找不到具体的查询。请帮我弄清楚。

我在 Elasticsearch 文档中存储的数据。它是 JSON 的形式,我需要它作为 JSON 来响应

  {
    "_index" : "recipe1",
    "_type" : "default",
    "_id" : "AWyPqNkb3frYFJ2__B8b",
    "_score" : 1.0,
    "_source" : {
      "message" : "[{\"id\":15,\"recipe_url\":\"https://www.example.com\",\"Channel\":\"Recipe\",\"Title\":\"Jamoo recipe\",\"Rating\":{\"id\":null,\"ratingValue\":4.625,\"bestRating\":5,\"worstRating\":1,\"ratingCount\":8},\"Timings\":{\"id\":null,\"cookTime\":\"PT5M\",\"prepTime\":\"PT5M\",\"totalTime\":\"PT10M\"},\"Author\":{\"id\":null,\"eval\":false,\"value\":\"JAMSHAID\",\"url\":\"https://www.example.com\",\"additionalInfo\":\"Recipe from Good Food magazine, \",\"description\":\"Substitute potatoes with pulses for a healthy alternative mash with a chunky texture\",\"published\":\"November 2011\"},\"Publication\":{\"id\":null,\"eval\":false,\"value\":\"\",\"url\":\"\",\"additionalInfo\":\"\",\"published\":\"\"},\"Nutrition\":\"per serving\",\"NutritionContents\":{\"id\":0,\"kcal\":183,\"fat\":\"5g\",\"saturates\":\"1g\",\"carbs\":\"25g\",\"sugars\":\"3g\",\"fibre\":\"7g\",\"protein\":\"11g\",\"salt\":\"0.84g\"},\"SkillLevel\":\"Easy\",\"Ingredients\":[\"1 tbsp olive oil, plus a drizzle to serve (optional)\",\"2 x 400g cans cannellini beans, rinsed and drained\",\"2 tbsp pesto\"],\"MakingMethod\":[\"Heat the oil in a large saucepan. Add the beans and cook for 3-4 mins until hot through. Lightly mash with a potato masher for a chunky texture. Stir through the pesto and season. To serve, drizzle with a little olive oil, if you like.\"],\"Keywords\":[\"Cannellini bean\",\"Cannellini beans\",\"Mash\",\"Beans\",\"Super healthy\",\"Pulses\",\"5-a-day\",\"Low fat\",\"Diet\",\"Dieting\",\"Side dish\",\"Bangers and mash\",\"Sausage and mash\",\"Texture\",\"Fireworks\",\"Pesto\",\"Easy\",\"Vegetarian\",\"Healthy\",\"Bonfire Night\"],\"Category\":[\"Side dish\",\"Dinner\"],\"Cousine\":\"Pakisttani\",\"Servings\":\"Serves 4\"}]"
    }
  },

完整方法

  @RequestMapping(value = "stringSearch", method = RequestMethod.GET)
public @ResponseBody
String getitem(@RequestParam("data") String title) {
    client.admin().indices().prepareRefresh().get();

    SearchResponse response = client.prepareSearch("recipe1")
            .addDocValueField("Title")
            .setSize(10)
            .get();


    SearchResponse scrollResp = client.prepareSearch()
            .setIndices("recipe1")
            .setTypes("default")
            .setSearchType(SearchType.QUERY_AND_FETCH)
          //  .setFetchSource(new String[]{"Title"}, null)
            .setQuery(QueryBuilders.queryStringQuery(title))
            .setSize(10).execute().actionGet();
    return scrollResp.toString();
}

在 Elasticsearch 中插入数据

    JSONObject jsonObject = new JSONObject();
    jsonObject.put("message", content1.toString());

其中 content1 是一个StringBuffer

Client client1 = new Config().client();
            System.out.println(client.toString());
            client1.prepareIndex("recipe1", "default").setSource(jsonObject).get();

建议更改后的堆栈跟踪

java.lang.NullPointerException
at java.base/java.util.Objects.requireNonNull(Objects.java:221)
at org.elasticsearch.action.index.IndexRequest.source(IndexRequest.java:464)
at org.elasticsearch.action.index.IndexRequest.source(IndexRequest.java:389)
at org.elasticsearch.action.index.IndexRequestBuilder.setSource(IndexRequestBuilder.java:131)
at com.techno.homes.search.ServicesPackage.MessageConsumerService.main(MessageConsumerService.java:88)

更改后 Elasticsearch 文档中的数据

{
    "_index" : "recipe",
    "_type" : "default",
    "_id" : "AWyUshs9VwfAdwghb9LK",
    "_score" : 1.0,
    "_source" : {
      "[{\"Timings\":{\"totalTime\":\"PT10M\",\"cookTime\":\"PT5M\",\"id\":null,\"prepTime\":\"PT5M\"},\"SkillLevel\":\"Easy\",\"Keywords\":[\"Cannellini bean\",\"Cannellini beans\",\"Mash\",\"Beans\",\"Super healthy\",\"Pulses\",\"5-a-day\",\"Low fat\",\"Diet\",\"Dieting\",\"Side dish\",\"Bangers and mash\",\"Sausage and mash\",\"Texture\",\"Fireworks\",\"Pesto\",\"Easy\",\"Vegetarian\",\"Healthy\",\"Bonfire Night\"],\"Category\":[\"Side dish\",\"Dinner\"],\"Nutrition\":\"per serving\",\"MakingMethod\":[\"Heat the oil in a large saucepan. Add the beans and cook for 3-4 mins until hot through. Lightly mash with a potato masher for a chunky texture. Stir through the pesto and season. To serve, drizzle with a little olive oil, if you like.\"],\"Cousine\":\"British\",\"Channel\":\"Recipe\",\"Rating\":{\"bestRating\":5,\"ratingValue\":4.625,\"id\":null,\"ratingCount\":8,\"worstRating\":1},\"Ingredients\":[\"1 tbsp olive oil, plus a drizzle to serve (optional)\",\"2 x 400g cans cannellini beans, rinsed and drained\",\"2 tbsp pesto\"],\"Servings\":\"Serves 4\",\"Title\":\"Bean & pesto mash\",\"Publication\":{\"eval\":false,\"additionalInfo\":\"\",\"id\":null,\"published\":\"\",\"value\":\"\",\"url\":\"\"},\"recipe_url\":\"https://www.techno-homes.com/recipes/1742637/bean-and-pesto-mash\",\"Author\":{\"eval\":false,\"additionalInfo\":\"Recipe from Good Food magazine, \",\"description\":\"Substitute potatoes with pulses for a healthy alternative mash with a chunky texture\",\"id\":null,\"published\":\"November 2011\",\"value\":\"Techno Homes\",\"url\":\"https://www.techno-homes.com/publication/good-food-0\"},\"id\":64,\"NutritionContents\":{\"kcal\":183,\"sugars\":\"3g\",\"salt\":\"0.84g\",\"carbs\":\"25g\",\"protein\":\"11g\",\"fat\":\"5g\",\"saturates\":\"1g\",\"id\":0,\"fibre\":\"7g\"}}]" : ""
    }

标签: javaspring-bootelasticsearchelasticsearch-5

解决方案


推荐阅读