Elasticsearch 之(45) Java API 基於upsert實現汽車最新價格的調整

作一個汽車零售數據的mapping,咱們要作的第一份數據,其實汽車信息java

PUT /car_shop
{
    "mappings": {
        "cars": {
            "properties": {
                "brand": {
                    "type": "text",
                    "analyzer": "ik_max_word",
                    "fields": {
                        "raw": {
                            "type": "keyword"
                        }
                    }
                },
                "name": {
                    "type": "text",
                    "analyzer": "ik_max_word",
                    "fields": {
                        "raw": {
                            "type": "keyword"
                        }
                    }
                }
            }
        }
    }
}

首先的話呢,第一次調整寶馬320這個汽車的售價,咱們但願將售價設置爲32萬,用一個upsert語法,若是這個汽車的信息以前不存在,那麼就insert,若是存在,那麼就updatejson

package com.es.app;


import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;

public class UpsertCarInfoApp {

    public static void main(String[] args) throws Exception{
        Settings settings = Settings.builder()
                .put("cluster.name", "elasticsearch")
                .put("client.transport.sniff", true)
                .build();

        TransportClient client = new PreBuiltTransportClient(settings)
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));

        IndexRequest indexRequest = new IndexRequest("car_shop", "cars", "1")
                .source(XContentFactory.jsonBuilder()
                        .startObject()
                        .field("brand", "寶馬")
                        .field("name", "寶馬320")
                        .field("price", 310000)
                        .field("produce_date", "2017-01-01")
                        .endObject()
                );
        UpdateRequest updateRequest = new UpdateRequest("car_shop", "cars", "1")
                .doc(XContentFactory.jsonBuilder()
                    .startObject()
                        .field("price", 310000)
                    .endObject())
                .upsert(indexRequest);

        UpdateResponse updateResponse = client.update(updateRequest).get();

        System.out.println(updateResponse.getVersion());
        client.close();
    }

}
相關文章
相關標籤/搜索