Java Code Examples for org.elasticsearch.action.index.IndexResponse#getId()

The following examples show how to use org.elasticsearch.action.index.IndexResponse#getId() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ElasticSearch.java    From hsweb-learning with Apache License 2.0 6 votes vote down vote up
private static void CreateIndex(Client client){
    String json = "{" +
            "\"user\":\"daiyutage\"," +
            "\"postDate\":\"2013-01-30\"," +
            "\"message\":\"trying out Elasticsearch\"" +
            "}";

    IndexResponse response = client.prepareIndex("twitter", "tweet","2")
            .setSource(json)
            .get();
    // Index name
    String _index = response.getIndex();
    System.out.println("index:"+_index);
    // Type name  
    String _type = response.getType();
    System.out.println("_type:"+_type);
    // Document ID (generated or not)  
    String _id = response.getId();
    // Version (if it's the first time you index this document, you will get: 1)  
    long _version = response.getVersion();
    System.out.println("_version:"+_version);
    // isCreated() is true if the document is a new one, false if it has been updated  
    boolean created = response.isCreated();

}
 
Example 2
Source File: TestTransportClient.java    From jframe with Apache License 2.0 6 votes vote down vote up
@Test
public void testIndex() throws IOException {
    IndexResponse response = client.prepareIndex("twitter", "tweet", "1").setSource(XContentFactory.jsonBuilder().startObject()
            .field("user", "kimchy").field("postDate", new Date()).field("message", "trying out Elasticsearch").endObject()).get();
    // Index name
    String _index = response.getIndex();
    // Type name
    String _type = response.getType();
    // Document ID (generated or not)
    String _id = response.getId();
    // Version (if it's the first time you index this document, you will
    // get: 1)
    long _version = response.getVersion();
    // isCreated() is true if the document is a new one, false if it has
    // been updated
    boolean created = response.isCreated();
    System.out.println(response.toString());

}
 
Example 3
Source File: ElasticSearchController.java    From springboot-learn with MIT License 6 votes vote down vote up
@PostMapping("add/book/novel")
public ResponseEntity add(@RequestParam(name = "title") String title,
                          @RequestParam(name = "author") String author,
                          @RequestParam(name = "wordCount") String wordCount,
                          @RequestParam(name = "publishDate") @DateTimeFormat(pattern = "yyyy-MM-dd") Date publishDate) {
    try {
        // 构建文档
        XContentBuilder contentBuilder = XContentFactory.jsonBuilder()
                .startObject()
                .field("title", title)
                .field("author", author)
                .field("word_count", wordCount)
                .field("publish_date", publishDate.getTime())
                .endObject();
        // 新增文档
        IndexResponse result = transportClient.prepareIndex(INDEX, TYPE)
                .setSource(contentBuilder)
                .get();
        return new ResponseEntity(result.getId(), HttpStatus.OK);
    } catch (IOException e) {
        LOGGER.error("add error", e);
        return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
 
Example 4
Source File: ElasticsearchAsyncIT.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Override
public void executeApp() throws Exception {
    client = Util.client(new InetSocketAddress("127.0.0.1", 9300));
    IndexResponse response = client.prepareIndex("testindex", "testtype")
            .setSource("abc", 11, "xyz", "some text")
            .get();
    documentId = response.getId();
    transactionMarker();
    client.close();
}
 
Example 5
Source File: ElasticsearchAsyncIT.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Override
public void executeApp() throws Exception {
    client = Util.client(new InetSocketAddress("127.0.0.1", 9300));
    IndexResponse response = client.prepareIndex("testindex", "testtype")
            .setSource("abc", 11, "xyz", "some text")
            .get();
    documentId = response.getId();
    transactionMarker();
    client.close();
}
 
Example 6
Source File: ElasticsearchAsyncIT.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Override
public void executeApp() throws Exception {
    client = Util.client(new InetSocketAddress("127.0.0.1", 9300));
    IndexResponse response = client.prepareIndex("testindex", "testtype")
            .setSource("abc", 11, "xyz", "some text")
            .get();
    documentId = response.getId();
    transactionMarker();
    client.close();
}
 
Example 7
Source File: ElasticsearchSyncIT.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Override
public void executeApp() throws Exception {
    client = Util.client(new InetSocketAddress("127.0.0.1", 9300));
    IndexResponse response = client.prepareIndex("testindex", "testtype")
            .setSource("abc", 11, "xyz", "some text")
            .get();
    documentId = response.getId();
    transactionMarker();
    client.close();
}
 
Example 8
Source File: TransportClient.java    From elasticsearch-jest-example with MIT License 5 votes vote down vote up
/**
 * 打印索引信息
 * @param response
 */
private static void printIndexInfo(IndexResponse response) {
	System.out.println("****************index ***********************");
	// Index name
	String _index = response.getIndex();
	// Type name
	String _type = response.getType();
	// Document ID (generated or not)
	String _id = response.getId();
	// Version (if it's the first time you index this document, you will get: 1)
	long _version = response.getVersion();
	System.out.println(_index+","+_type+","+_id+","+_version);
}
 
Example 9
Source File: ElasticsearchSyncIT.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Override
public void executeApp() throws Exception {
    client = Util.client(new InetSocketAddress("127.0.0.1", 9300));
    IndexResponse response = client.prepareIndex("testindex", "testtype")
            .setSource("abc", 11, "xyz", "some text")
            .get();
    documentId = response.getId();
    transactionMarker();
    client.close();
}
 
Example 10
Source File: CommonWebpageDAO.java    From spider with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String index(Webpage webpage) {
    IndexResponse indexResponse = null;
    try {
        indexResponse = client.prepareIndex(INDEX_NAME, TYPE_NAME)
                .setSource(gson.toJson(webpage))
                .get();
        return indexResponse.getId();
    } catch (Exception e) {
        LOG.error("索引 Webpage 出错," + e.getLocalizedMessage());
    }
    return null;
}
 
Example 11
Source File: CommonWebpageDAO.java    From Gather-Platform with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String index(Webpage webpage) {
    IndexResponse indexResponse = null;
    try {
        indexResponse = client.prepareIndex(INDEX_NAME, TYPE_NAME)
                .setSource(gson.toJson(webpage))
                .get();
        return indexResponse.getId();
    } catch (Exception e) {
        LOG.error("索引 Webpage 出错," + e.getLocalizedMessage());
    }
    return null;
}
 
Example 12
Source File: SpiderInfoDAO.java    From Gather-Platform with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String index(SpiderInfo spiderInfo) {
    IndexResponse indexResponse;
    if (getByDomain(spiderInfo.getDomain(), 10, 1).size() > 0) {
        List<SpiderInfo> mayDuplicate = Lists.newLinkedList();
        List<SpiderInfo> temp;
        int i = 1;
        do {
            temp = getByDomain(spiderInfo.getDomain(), 100, i++);
            mayDuplicate.addAll(temp);
        } while (temp.size() > 0);
        if (mayDuplicate.indexOf(spiderInfo) != -1 && (spiderInfo = mayDuplicate.get(mayDuplicate.indexOf(spiderInfo))) != null) {
            LOG.warn("已经含有此模板,不再存储");
            return spiderInfo.getId();
        }
    }
    try {
        indexResponse = client.prepareIndex(INDEX_NAME, TYPE_NAME)
                .setSource(gson.toJson(spiderInfo))
                .get();
        LOG.debug("索引爬虫模板成功");
        return indexResponse.getId();
    } catch (Exception e) {
        LOG.error("索引 Webpage 出错," + e.getLocalizedMessage());
    }
    return null;
}
 
Example 13
Source File: ESClientTest.java    From emotional_analysis with Apache License 2.0 5 votes vote down vote up
@Test
    public void test1() throws Exception {
        XContentBuilder source = createJson4();
        // 存json入索引中
        IndexResponse response = client.prepareIndex("twitter", "tweet", "1").setSource(source).get();
//        // 结果获取
        String index = response.getIndex();
        String type = response.getType();
        String id = response.getId();
        long version = response.getVersion();
        boolean created = response.isCreated();
        System.out.println(index + " : " + type + ": " + id + ": " + version + ": " + created);
    }
 
Example 14
Source File: ESOpt.java    From common-project with Apache License 2.0 5 votes vote down vote up
/**
 * 数据添加,正定ID
 * @param bean  要增加的数据
 * @param index 索引,类似数据库
 * @param type  类型,类似表
 * @param id    数据ID
 * @return
 */
public static String addData(Object bean, String index, String type, String id) {
    JSONObject jsonObject = (JSONObject) JSON.parse(JSON.toJSONString(bean));
    IndexResponse response = client.prepareIndex(index, type, id).setSource(jsonObject).get();

    logger.info("addData response status:{},id:{}", response.status().getStatus(), response.getId());

    return response.getId();
}
 
Example 15
Source File: Application.java    From ElasticSearch with MIT License 5 votes vote down vote up
@PostMapping("/add/book/novel")
public ResponseEntity add(
        @RequestParam(name = "title") String title,
        @RequestParam(name = "author") String author,
        @RequestParam(name = "word_count") int wordCount,
        @RequestParam(name = "publish_date")
        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date publishDate) {

    try {
        XContentBuilder content = XContentFactory.jsonBuilder().startObject()
                .field("title", title)
                .field("author", author)
                .field("word_count", wordCount)
                .field("publish_date", publishDate.getTime())
                .endObject();

        IndexResponse response = client.prepareIndex(BOOK_INDEX, BOOK_TYPE_NOVEL)
                .setSource(content)
                .get();

        return new ResponseEntity(response.getId(), HttpStatus.OK);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
    }

}
 
Example 16
Source File: BookingDaoESImp.java    From blue-marlin with Apache License 2.0 5 votes vote down vote up
public String createBookingBucket(BookingBucket bookingBucket) throws IOException
{
    Map sourceMap = CommonUtil.convertToMap(bookingBucket);
    IndexRequest indexRequest = new IndexRequest(this.bookingBucketsIndex, ES_TYPE);
    indexRequest.source(sourceMap);
    IndexResponse indexResponse = esclient.index(indexRequest, WriteRequest.RefreshPolicy.WAIT_UNTIL.getValue());
    return indexResponse.getId();
}
 
Example 17
Source File: BookingDaoESImp.java    From blue-marlin with Apache License 2.0 5 votes vote down vote up
@Override
public String createBooking(Booking booking) throws IOException
{
    Map sourceMap = CommonUtil.convertToMap(booking);
    IndexRequest indexRequest = new IndexRequest(this.bookingsIndex, ES_TYPE);
    indexRequest.source(sourceMap);
    IndexResponse indexResponse = esclient.index(indexRequest, WriteRequest.RefreshPolicy.WAIT_UNTIL.getValue());
    return indexResponse.getId();
}
 
Example 18
Source File: LoggingIT.java    From elasticsearch-learning-to-rank with Apache License 2.0 4 votes vote down vote up
public void indexDoc(Doc d) {
    IndexResponse resp = client().prepareIndex("test_index", "test")
            .setSource("field1", d.field1, "field2", d.field2, "scorefield1", d.scorefield1, "nesteddocs1", d.getNesteddocs1())
            .get();
    d.id = resp.getId();
}
 
Example 19
Source File: ESJavaRDDFT.java    From deep-spark with Apache License 2.0 4 votes vote down vote up
/**
 * Imports dataset
 *
 * @throws java.io.IOException
 */
private static void dataSetImport()
        throws IOException, ExecutionException, IOException, InterruptedException, ParseException {

    JSONParser parser = new JSONParser();
    URL url = Resources.getResource(DATA_SET_NAME);
    Object obj = parser.parse(new FileReader(url.getFile()));

    JSONObject jsonObject = (JSONObject) obj;

    IndexResponse responseBook = client.prepareIndex(ES_INDEX_BOOK, ES_TYPE_INPUT, "id")
            .setSource(jsonObject.toJSONString())
            .execute()
            .actionGet();

    String json2 = "{" +

            "\"message\":\"" + MESSAGE_TEST + "\"" +
            "}";

    IndexResponse response2 = client.prepareIndex(ES_INDEX_MESSAGE, ES_TYPE_MESSAGE).setCreate(true)
            .setSource(json2).setReplicationType(ReplicationType.ASYNC)
            .execute()
            .actionGet();

    String json = "{" +
            "\"user\":\"kimchy\"," +
            "\"postDate\":\"2013-01-30\"," +
            "\"message\":\"trying out Elasticsearch\"" +
            "}";

    IndexResponse response = client.prepareIndex(ES_INDEX, ES_TYPE).setCreate(true)
            .setSource(json)
            .execute()
            .actionGet();

    String index = response.getIndex();
    String _type = response.getType();
    String _id = response.getId();
    try {
        CountResponse countResponse = client.prepareCount(ES_INDEX).setTypes(ES_TYPE)
                .execute()
                .actionGet();

        SearchResponse searchResponse = client.prepareSearch(ES_INDEX_BOOK).setTypes(ES_TYPE_INPUT)
                .execute()
                .actionGet();

        //searchResponse.getHits().hits();
        //assertEquals(searchResponse.getCount(), 1);
    } catch (AssertionError | Exception e) {
        cleanup();
        e.printStackTrace();
    }
}
 
Example 20
Source File: ElasticsearchUtil.java    From SpringBootLearn with Apache License 2.0 2 votes vote down vote up
/**
 * 数据添加,正定ID
 * @param jsonObject 要增加的数据
 * @param index      索引,类似数据库
 * @param type       类型,类似表
 * @param id         数据ID(为空默认生成)
 * @return
 */
public static String addData(JSONObject jsonObject, String index, String type, String id) {
    IndexResponse response = client.prepareIndex(index, type, id).setSource(jsonObject).get();
    log.info("addData response status:{},id:{}", response.status().getStatus(), response.getId());
    return response.getId();
}