Elasticsearch simple contains search using Java API

孤者浪人 提交于 2019-12-13 06:36:41

问题


I'm trying to play with Java API of Elastic Search and struggling to find the right querybuilder to use.

My JSON has got fields like: name, description etc.

My JSON (One sample):

{ 
    "_id" : { "$oid" : "5160988c96cc620a5db6dafa" },
    "name" : "Spinach Strata Recipe", 
    "ingredients" : "8 ounces day-old crusty bread, such as pain au levain, large dice (about 6 cups)\n2 cups coarsely chopped baby spinach leaves (about 3 1/2 ounces)\n3/4 cup crumbled provolone cheese (about 3 3/4 ounces)\n2 tablespoons extra-virgin olive oil, plus more for coating the pan\n1 tablespoon finely grated lemon zest (from about 1 medium lemon)\n2 teaspoons Dijon mustard\n1/8teaspoon kosher salt\n1/2 teaspoon freshly ground black pepper\n6 ex   large eggs\n2 cups whole milk\n1/2 teaspoon finely chopped fresh oregano leaves", 
    "url" : "http://www.chow.com/users/recipes/29915-spinach-strata",     
    "image" : null,
    "ts" : { "$date" : 1365285004038 },
    "cookTime" : null,
    "source" : "chow",
    "recipeYield" : "6 servings",
    "prepTime" : null,
    "description" : "Aside from being comforting and filling, stratas are really easy to make. Whisked eggs and milk are poured over bread and your favorite fillings, then everything..." 
}

This is how I"m indexing:

Settings settings = ImmutableSettings.settingsBuilder().put("cluster.name", "elasticsearch_sai").build();
    final TransportClient client = new TransportClient(settings);
    Client _client = client.addTransportAddress(new InetSocketTransportAddress("localhost", Integer.parseInt("9300")));
    reader.lines().limit(10000).forEach(json -> {
        IndexResponse response = _client.prepareIndex("openrecipe", "recipe")
                .setSource(json)
                .execute()
                .actionGet();
     System.out.println("Indexed: "+response.getId()+" --> "+response.isCreated());
    });

    _client.admin().indices().prepareRefresh().execute().actionGet()   ;

I want to search all the documents which has got the word sandwich in the name field (case insensitive).

But this doesn't work:

   SearchResponse response = _client.prepareSearch("openrecipe")        
       .setTypes("recipe")                                          
       .setFrom(0).setSize(60)                                      
       .setSearchType(SearchType.QUERY_AND_FETCH)                   
       .setQuery(QueryBuilders.termQuery("name", "sandwich"))       
       .execute()                                                   
       .actionGet();                                                

来源:https://stackoverflow.com/questions/31771110/elasticsearch-simple-contains-search-using-java-api

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!