简体   繁体   中英

Elasticsearch simple index and search JSON using Java API

My first attempt with Elasticsearch and I find a ton of documentation available on the web and was trying a simple example.

I'm using the Elasticsearch Java API to Index 10000 JSON documents using the standard settings and searching them.

HEre is the code:

GZIPInputStream in = new GZIPInputStream(new URL("file:/Users/sai/temp/recipeitems-latest.json.gz").openStream());

    ObjectMapper mapper = new ObjectMapper();
    BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
    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().parallel().limit(10000).forEach(json -> {
        IndexResponse response = _client.prepareIndex("openrecipe", "recipe")
                .setSource(json)
                .execute()
                .actionGet();
     System.out.println("Indexed: "+response.getId()+" --> "+response.isCreated());
    });

    SearchResponse response = _client.prepareSearch("openrecipe")
            .setTypes("recipe")
            .setFrom(0).setSize(60)
            .addField("name")
            .execute()
            .actionGet();

    Stream.of(response.getHits().getHits()).forEach(hit -> System.out.println(hit.getSourceAsString()));

I'm really struggling as the search is not returning any results. I see a 60 nulls returned in the console.

Also, I tried with a few query but no luck. I don't know whether the indexing is wrong or the searching is wrong.

My JSON has fields like: "name", "description" etc. I'm trying to do a case insensitive simple contains search on fields (not exact match).

What am I missing here?

After indexing, try using :

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

This should reindex elements into ES.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM