当前位置: 首页>>代码示例>>Java>>正文


Java BytesArray类代码示例

本文整理汇总了Java中org.elasticsearch.common.bytes.BytesArray的典型用法代码示例。如果您正苦于以下问题:Java BytesArray类的具体用法?Java BytesArray怎么用?Java BytesArray使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


BytesArray类属于org.elasticsearch.common.bytes包,在下文中一共展示了BytesArray类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: testTakePositionOffsetGapIntoAccount

import org.elasticsearch.common.bytes.BytesArray; //导入依赖的package包/类
public void testTakePositionOffsetGapIntoAccount() throws Exception {
    createIndex("test", client().admin().indices().prepareCreate("test")
            .addMapping("type", "field", "type=text,position_increment_gap=5")
            .addMapping("queries", "query", "type=percolator")
    );
    client().prepareIndex("test", "queries", "1")
            .setSource(jsonBuilder().startObject().field("query",
                    new MatchPhraseQueryBuilder("field", "brown fox").slop(4)).endObject())
            .get();
    client().prepareIndex("test", "queries", "2")
            .setSource(jsonBuilder().startObject().field("query",
                    new MatchPhraseQueryBuilder("field", "brown fox").slop(5)).endObject())
            .get();
    client().admin().indices().prepareRefresh().get();

    SearchResponse response = client().prepareSearch().setQuery(
            new PercolateQueryBuilder("query", "type", new BytesArray("{\"field\" : [\"brown\", \"fox\"]}"), XContentType.JSON)
    ).get();
    assertHitCount(response, 1);
    assertThat(response.getHits().getAt(0).getId(), equalTo("2"));
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:22,代码来源:PercolatorQuerySearchIT.java

示例2: testCBORBasedOnMajorObjectDetection

import org.elasticsearch.common.bytes.BytesArray; //导入依赖的package包/类
public void testCBORBasedOnMajorObjectDetection() {
    // for this {"f "=> 5} perl encoder for example generates:
    byte[] bytes = new byte[] {(byte) 0xA1, (byte) 0x43, (byte) 0x66, (byte) 6f, (byte) 6f, (byte) 0x5};
    assertThat(XContentFactory.xContentType(bytes), equalTo(XContentType.CBOR));
    //assertThat(((Number) XContentHelper.convertToMap(bytes, true).v2().get("foo")).intValue(), equalTo(5));

    // this if for {"foo" : 5} in python CBOR
    bytes = new byte[] {(byte) 0xA1, (byte) 0x63, (byte) 0x66, (byte) 0x6f, (byte) 0x6f, (byte) 0x5};
    assertThat(XContentFactory.xContentType(bytes), equalTo(XContentType.CBOR));
    assertThat(((Number) XContentHelper.convertToMap(new BytesArray(bytes), true).v2().get("foo")).intValue(), equalTo(5));

    // also make sure major type check doesn't collide with SMILE and JSON, just in case
    assertThat(CBORConstants.hasMajorType(CBORConstants.MAJOR_TYPE_OBJECT, SmileConstants.HEADER_BYTE_1), equalTo(false));
    assertThat(CBORConstants.hasMajorType(CBORConstants.MAJOR_TYPE_OBJECT, (byte) '{'), equalTo(false));
    assertThat(CBORConstants.hasMajorType(CBORConstants.MAJOR_TYPE_OBJECT, (byte) ' '), equalTo(false));
    assertThat(CBORConstants.hasMajorType(CBORConstants.MAJOR_TYPE_OBJECT, (byte) '-'), equalTo(false));
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:18,代码来源:XContentFactoryTests.java

示例3: getExistingDigestsFromTarget

import org.elasticsearch.common.bytes.BytesArray; //导入依赖的package包/类
private Set<BytesArray> getExistingDigestsFromTarget(byte prefix) {
    BlobStartPrefixResponse response =
        (BlobStartPrefixResponse)transportService.submitRequest(
            request.targetNode(),
            BlobRecoveryTarget.Actions.START_PREFIX,
            new BlobStartPrefixSyncRequest(request.recoveryId(), request.shardId(), prefix),
            TransportRequestOptions.EMPTY,
            new FutureTransportResponseHandler<TransportResponse>() {
                @Override
                public TransportResponse newInstance() {
                    return new BlobStartPrefixResponse();
                }
            }
        ).txGet();

    Set<BytesArray> result = new HashSet<BytesArray>();
    for (byte[] digests : response.existingDigests) {
        result.add(new BytesArray(digests));
    }
    return result;
}
 
开发者ID:baidu,项目名称:Elasticsearch,代码行数:22,代码来源:BlobRecoveryHandler.java

示例4: testToString

import org.elasticsearch.common.bytes.BytesArray; //导入依赖的package包/类
public void testToString() {
    GetResponse getResponse = new GetResponse(
            new GetResult("index", "type", "id", 1, true, new BytesArray("{ \"field1\" : " + "\"value1\", \"field2\":\"value2\"}"),
                    Collections.singletonMap("field1", new GetField("field1", Collections.singletonList("value1")))));
    assertEquals("{\"_index\":\"index\",\"_type\":\"type\",\"_id\":\"id\",\"_version\":1,\"found\":true,\"_source\":{ \"field1\" "
            + ": \"value1\", \"field2\":\"value2\"},\"fields\":{\"field1\":[\"value1\"]}}", getResponse.toString());
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:8,代码来源:GetResponseTests.java

示例5: testIncludes

import org.elasticsearch.common.bytes.BytesArray; //导入依赖的package包/类
public void testIncludes() throws Exception {
    String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
        .startObject("_source").array("includes", new String[]{"path1*"}).endObject()
        .endObject().endObject().string();

    DocumentMapper documentMapper = createIndex("test").mapperService().documentMapperParser().parse("type", new CompressedXContent(mapping));

    ParsedDocument doc = documentMapper.parse("test", "type", "1", XContentFactory.jsonBuilder().startObject()
        .startObject("path1").field("field1", "value1").endObject()
        .startObject("path2").field("field2", "value2").endObject()
        .endObject().bytes());

    IndexableField sourceField = doc.rootDoc().getField("_source");
    Map<String, Object> sourceAsMap;
    try (XContentParser parser = createParser(JsonXContent.jsonXContent, new BytesArray(sourceField.binaryValue()))) {
        sourceAsMap = parser.map();
    }
    assertThat(sourceAsMap.containsKey("path1"), equalTo(true));
    assertThat(sourceAsMap.containsKey("path2"), equalTo(false));
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:21,代码来源:SourceFieldMapperTests.java

示例6: testInitialSearchEntity

import org.elasticsearch.common.bytes.BytesArray; //导入依赖的package包/类
public void testInitialSearchEntity() throws IOException {
    SearchRequest searchRequest = new SearchRequest();
    searchRequest.source(new SearchSourceBuilder());
    String query = "{\"match_all\":{}}";
    HttpEntity entity = initialSearchEntity(searchRequest, new BytesArray(query));
    assertEquals(ContentType.APPLICATION_JSON.toString(), entity.getContentType().getValue());
    assertEquals("{\"query\":" + query + ",\"_source\":true}",
            Streams.copyToString(new InputStreamReader(entity.getContent(), StandardCharsets.UTF_8)));

    // Source filtering is included if set up
    searchRequest.source().fetchSource(new String[] {"in1", "in2"}, new String[] {"out"});
    entity = initialSearchEntity(searchRequest, new BytesArray(query));
    assertEquals(ContentType.APPLICATION_JSON.toString(), entity.getContentType().getValue());
    assertEquals("{\"query\":" + query + ",\"_source\":{\"includes\":[\"in1\",\"in2\"],\"excludes\":[\"out\"]}}",
            Streams.copyToString(new InputStreamReader(entity.getContent(), StandardCharsets.UTF_8)));

    // Invalid XContent fails
    RuntimeException e = expectThrows(RuntimeException.class,
            () -> initialSearchEntity(searchRequest, new BytesArray("{}, \"trailing\": {}")));
    assertThat(e.getCause().getMessage(), containsString("Unexpected character (',' (code 44))"));
    e = expectThrows(RuntimeException.class, () -> initialSearchEntity(searchRequest, new BytesArray("{")));
    assertThat(e.getCause().getMessage(), containsString("Unexpected end-of-input"));
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:24,代码来源:RemoteRequestBuildersTests.java

示例7: setContent

import org.elasticsearch.common.bytes.BytesArray; //导入依赖的package包/类
public void setContent(final String source, final ContentType contentType) throws UnsupportedCharsetException {
    Args.notNull(source, "Source string");
    Charset charset = contentType != null?contentType.getCharset():null;
    if(charset == null) {
        charset = HTTP.DEF_CONTENT_CHARSET;
    }

    try {
        this.content = new BytesArray(source.getBytes(charset.name()));
    } catch (UnsupportedEncodingException var) {
        throw new UnsupportedCharsetException(charset.name());
    }

    if(contentType != null) {
        addHeader("Content-Type", contentType.toString());
    }
}
 
开发者ID:baidu,项目名称:Elasticsearch,代码行数:18,代码来源:LocalRestRequest.java

示例8: testUpdateByQueryCancel

import org.elasticsearch.common.bytes.BytesArray; //导入依赖的package包/类
public void testUpdateByQueryCancel() throws Exception {
    BytesReference pipeline = new BytesArray("{\n" +
            "  \"description\" : \"sets processed to true\",\n" +
            "  \"processors\" : [ {\n" +
            "      \"test\" : {}\n" +
            "  } ]\n" +
            "}");
    assertAcked(client().admin().cluster().preparePutPipeline("set-processed", pipeline, XContentType.JSON).get());

    testCancel(UpdateByQueryAction.NAME, updateByQuery().setPipeline("set-processed").source(INDEX), (response, total, modified) -> {
        assertThat(response, matcher().updated(modified).reasonCancelled(equalTo("by user request")));
        assertHitCount(client().prepareSearch(INDEX).setSize(0).setQuery(termQuery("processed", true)).get(), modified);
    }, equalTo("update-by-query [" + INDEX + "]"));

    assertAcked(client().admin().cluster().deletePipeline(new DeletePipelineRequest("set-processed")).get());
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:17,代码来源:CancelTests.java

示例9: testTaskInfoToString

import org.elasticsearch.common.bytes.BytesArray; //导入依赖的package包/类
public void testTaskInfoToString() {
    String nodeId = randomAsciiOfLength(10);
    long taskId = randomIntBetween(0, 100000);
    long startTime = randomNonNegativeLong();
    long runningTime = randomNonNegativeLong();
    boolean cancellable = randomBoolean();
    TaskInfo taskInfo = new TaskInfo(new TaskId(nodeId, taskId), "test_type",
        "test_action", "test_description", null, startTime, runningTime, cancellable, TaskId.EMPTY_TASK_ID);
    String taskInfoString = taskInfo.toString();
    Map<String, Object> map = XContentHelper.convertToMap(new BytesArray(taskInfoString.getBytes(StandardCharsets.UTF_8)), true).v2();
    assertEquals(((Number)map.get("id")).longValue(), taskId);
    assertEquals(map.get("type"), "test_type");
    assertEquals(map.get("action"), "test_action");
    assertEquals(map.get("description"), "test_description");
    assertEquals(((Number)map.get("start_time_in_millis")).longValue(), startTime);
    assertEquals(((Number)map.get("running_time_in_nanos")).longValue(), runningTime);
    assertEquals(map.get("cancellable"), cancellable);
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:19,代码来源:TaskTests.java

示例10: testCrud

import org.elasticsearch.common.bytes.BytesArray; //导入依赖的package包/类
public void testCrud() throws Exception {
    String id = "_id";
    Pipeline pipeline = store.get(id);
    assertThat(pipeline, nullValue());
    ClusterState clusterState = ClusterState.builder(new ClusterName("_name")).build(); // Start empty

    PutPipelineRequest putRequest = new PutPipelineRequest(id,
            new BytesArray("{\"processors\": [{\"set\" : {\"field\": \"_field\", \"value\": \"_value\"}}]}"), XContentType.JSON);
    ClusterState previousClusterState = clusterState;
    clusterState = store.innerPut(putRequest, clusterState);
    store.innerUpdatePipelines(previousClusterState, clusterState);
    pipeline = store.get(id);
    assertThat(pipeline, notNullValue());
    assertThat(pipeline.getId(), equalTo(id));
    assertThat(pipeline.getDescription(), nullValue());
    assertThat(pipeline.getProcessors().size(), equalTo(1));
    assertThat(pipeline.getProcessors().get(0).getType(), equalTo("set"));

    DeletePipelineRequest deleteRequest = new DeletePipelineRequest(id);
    previousClusterState = clusterState;
    clusterState = store.innerDelete(deleteRequest, clusterState);
    store.innerUpdatePipelines(previousClusterState, clusterState);
    pipeline = store.get(id);
    assertThat(pipeline, nullValue());
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:26,代码来源:PipelineStoreTests.java

示例11: verify

import org.elasticsearch.common.bytes.BytesArray; //导入依赖的package包/类
@Override
public void verify(String seed) {
    BlobContainer testBlobContainer = blobStore.blobContainer(basePath.add(testBlobPrefix(seed)));
    DiscoveryNode localNode = clusterService.localNode();
    if (testBlobContainer.blobExists("master.dat")) {
        try  {
            testBlobContainer.writeBlob("data-" + localNode.getId() + ".dat", new BytesArray(seed));
        } catch (IOException exp) {
            throw new RepositoryVerificationException(repositoryName, "store location [" + blobStore + "] is not accessible on the node [" + localNode + "]", exp);
        }
    } else {
        throw new RepositoryVerificationException(repositoryName, "a file written by master to the store [" + blobStore + "] cannot be accessed on the node [" + localNode + "]. "
                + "This might indicate that the store [" + blobStore + "] is not shared between this node and the master node or "
                + "that permissions on the store don't allow reading files written by the master node");
    }
}
 
开发者ID:baidu,项目名称:Elasticsearch,代码行数:17,代码来源:BlobStoreIndexShardRepository.java

示例12: start

import org.elasticsearch.common.bytes.BytesArray; //导入依赖的package包/类
private Status start(ChannelBuffer buffer, boolean last) {
    logger.trace("start blob upload");
    assert (transferId == null);
    StartBlobRequest request = new StartBlobRequest(
            index,
            Hex.decodeHex(digest),
            new BytesArray(buffer.array()),
            last
    );
    transferId = request.transferId();
    size += buffer.readableBytes();

    startResponse = client.execute(StartBlobAction.INSTANCE, request).actionGet();
    status = startResponse.status();
    return status;
}
 
开发者ID:baidu,项目名称:Elasticsearch,代码行数:17,代码来源:RemoteDigestBlob.java

示例13: initValues

import org.elasticsearch.common.bytes.BytesArray; //导入依赖的package包/类
private void initValues(Terms curTerms, PostingsEnum posEnum, int termFreq) throws IOException {
    for (int j = 0; j < termFreq; j++) {
        int nextPos = posEnum.nextPosition();
        if (curTerms.hasPositions()) {
            currentPositions[j] = nextPos;
        }
        if (curTerms.hasOffsets()) {
            currentStartOffset[j] = posEnum.startOffset();
            currentEndOffset[j] = posEnum.endOffset();
        }
        if (curTerms.hasPayloads()) {
            BytesRef curPayload = posEnum.getPayload();
            if (curPayload != null) {
                currentPayloads[j] = new BytesArray(curPayload.bytes, 0, curPayload.length);
            } else {
                currentPayloads[j] = null;
            }
        }
    }
}
 
开发者ID:baidu,项目名称:Elasticsearch,代码行数:21,代码来源:TermVectorsResponse.java

示例14: innerExecute

import org.elasticsearch.common.bytes.BytesArray; //导入依赖的package包/类
@Override
public TermSuggestion innerExecute(String name, TermSuggestionContext suggestion, IndexSearcher searcher, CharsRefBuilder spare) throws IOException {
    DirectSpellChecker directSpellChecker = SuggestUtils.getDirectSpellChecker(suggestion.getDirectSpellCheckerSettings());
    final IndexReader indexReader = searcher.getIndexReader();
    TermSuggestion response = new TermSuggestion(
            name, suggestion.getSize(), suggestion.getDirectSpellCheckerSettings().sort()
    );
    List<Token> tokens = queryTerms(suggestion, spare);
    for (Token token : tokens) {
        // TODO: Extend DirectSpellChecker in 4.1, to get the raw suggested words as BytesRef
        SuggestWord[] suggestedWords = directSpellChecker.suggestSimilar(
                token.term, suggestion.getShardSize(), indexReader, suggestion.getDirectSpellCheckerSettings().suggestMode()
        );
        Text key = new Text(new BytesArray(token.term.bytes()));
        TermSuggestion.Entry resultEntry = new TermSuggestion.Entry(key, token.startOffset, token.endOffset - token.startOffset);
        for (SuggestWord suggestWord : suggestedWords) {
            Text word = new Text(suggestWord.string);
            resultEntry.addOption(new TermSuggestion.Entry.Option(word, suggestWord.freq, suggestWord.score));
        }
        response.addTerm(resultEntry);
    }
    return response;
}
 
开发者ID:baidu,项目名称:Elasticsearch,代码行数:24,代码来源:TermSuggester.java

示例15: handleFavicon

import org.elasticsearch.common.bytes.BytesArray; //导入依赖的package包/类
void handleFavicon(RestRequest request, RestChannel channel) {
    if (request.method() == RestRequest.Method.GET) {
        try {
            try (InputStream stream = getClass().getResourceAsStream("/config/favicon.ico")) {
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                Streams.copy(stream, out);
                BytesRestResponse restResponse = new BytesRestResponse(RestStatus.OK, "image/x-icon", out.toByteArray());
                channel.sendResponse(restResponse);
            }
        } catch (IOException e) {
            channel.sendResponse(new BytesRestResponse(INTERNAL_SERVER_ERROR, BytesRestResponse.TEXT_CONTENT_TYPE, BytesArray.EMPTY));
        }
    } else {
        channel.sendResponse(new BytesRestResponse(FORBIDDEN, BytesRestResponse.TEXT_CONTENT_TYPE, BytesArray.EMPTY));
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:17,代码来源:RestController.java


注:本文中的org.elasticsearch.common.bytes.BytesArray类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。