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


Java Builder.put方法代码示例

本文整理汇总了Java中org.elasticsearch.common.settings.Settings.Builder.put方法的典型用法代码示例。如果您正苦于以下问题:Java Builder.put方法的具体用法?Java Builder.put怎么用?Java Builder.put使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在org.elasticsearch.common.settings.Settings.Builder的用法示例。


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

示例1: getSettings

import org.elasticsearch.common.settings.Settings.Builder; //导入方法依赖的package包/类
private Settings getSettings(int nodeOrdinal, long nodeSeed, Settings others) {
    Builder builder = Settings.builder().put(defaultSettings)
        .put(getRandomNodeSettings(nodeSeed));
    Settings settings = nodeConfigurationSource.nodeSettings(nodeOrdinal);
    if (settings != null) {
        if (settings.get(ClusterName.CLUSTER_NAME_SETTING.getKey()) != null) {
            throw new IllegalStateException("Tests must not set a '" + ClusterName.CLUSTER_NAME_SETTING.getKey() + "' as a node setting set '" + ClusterName.CLUSTER_NAME_SETTING.getKey() + "': [" + settings.get(ClusterName.CLUSTER_NAME_SETTING.getKey()) + "]");
        }
        builder.put(settings);
    }
    if (others != null) {
        builder.put(others);
    }
    builder.put(ClusterName.CLUSTER_NAME_SETTING.getKey(), clusterName);
    return builder.build();
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:17,代码来源:InternalTestCluster.java

示例2: indexRandomNumbers

import org.elasticsearch.common.settings.Settings.Builder; //导入方法依赖的package包/类
private int indexRandomNumbers(String analyzer, int shards, boolean dummyDocs) throws Exception {
    Builder builder = Settings.builder().put(indexSettings());

    if (shards > 0) {
        builder.put(SETTING_NUMBER_OF_SHARDS, shards);
    }

    assertAcked(prepareCreate("test")
            .addMapping(
                    "type1",
                    jsonBuilder().startObject().startObject("type1").startObject("properties").startObject("field1")
                            .field("analyzer", analyzer).field("type", "text").endObject().endObject().endObject().endObject())
            .setSettings(builder));
    int numDocs = randomIntBetween(100, 150);
    IndexRequestBuilder[] docs = new IndexRequestBuilder[numDocs];
    for (int i = 0; i < numDocs; i++) {
        docs[i] = client().prepareIndex("test", "type1", String.valueOf(i)).setSource("field1", English.intToEnglish(i));
    }

    indexRandom(true, dummyDocs, docs);
    ensureGreen();
    return numDocs;
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:24,代码来源:QueryRescorerIT.java

示例3: testFromSize

import org.elasticsearch.common.settings.Settings.Builder; //导入方法依赖的package包/类
public void testFromSize() throws Exception {
    Builder settings = Settings.builder();
    settings.put(SETTING_NUMBER_OF_SHARDS, 1);
    settings.put(SETTING_NUMBER_OF_REPLICAS, 0);
    assertAcked(prepareCreate("test").setSettings(settings));
    for(int i=0;i<5;i++) {
        client().prepareIndex("test", "type", ""+i).setSource("text", "hello world").get();
    }
    refresh();

    SearchRequestBuilder request = client().prepareSearch();
    request.setQuery(QueryBuilders.termQuery("text", "hello"));
    request.setFrom(1);
    request.setSize(4);
    request.addRescorer(RescoreBuilder.queryRescorer(QueryBuilders.matchAllQuery()), 50);

    assertEquals(4, request.get().getHits().getHits().length);
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:19,代码来源:QueryRescorerIT.java

示例4: testBackwardsCompatibilityEdgeNgramTokenFilter

import org.elasticsearch.common.settings.Settings.Builder; //导入方法依赖的package包/类
public void testBackwardsCompatibilityEdgeNgramTokenFilter() throws Exception {
    int iters = scaledRandomIntBetween(20, 100);
    for (int i = 0; i < iters; i++) {
        final Index index = new Index("test", "_na_");
        final String name = "ngr";
        Version v = randomVersion(random());
        Builder builder = newAnalysisSettingsBuilder().put("min_gram", 2).put("max_gram", 3);
        boolean reverse = random().nextBoolean();
        if (reverse) {
            builder.put("side", "back");
        }
        Settings settings = builder.build();
        Settings indexSettings = newAnalysisSettingsBuilder().put(IndexMetaData.SETTING_VERSION_CREATED, v.id).build();
        Tokenizer tokenizer = new MockTokenizer();
        tokenizer.setReader(new StringReader("foo bar"));
        TokenStream edgeNGramTokenFilter = new EdgeNGramTokenFilterFactory(IndexSettingsModule.newIndexSettings(index, indexSettings), null, name, settings).create(tokenizer);
        if (reverse) {
            assertThat(edgeNGramTokenFilter, instanceOf(ReverseStringFilter.class));
        } else {
            assertThat(edgeNGramTokenFilter, instanceOf(EdgeNGramTokenFilter.class));
        }
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:24,代码来源:NGramTokenizerFactoryTests.java

示例5: testCorrectPositionIncrementSetting

import org.elasticsearch.common.settings.Settings.Builder; //导入方法依赖的package包/类
public void testCorrectPositionIncrementSetting() throws IOException {
    Builder builder = Settings.builder().put("index.analysis.filter.my_stop.type", "stop");
    if (random().nextBoolean()) {
        builder.put("index.analysis.filter.my_stop.version", Version.LATEST);
    } else {
        // don't specify
    }
    builder.put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString());
    ESTestCase.TestAnalysis analysis = AnalysisTestsHelper.createTestAnalysisFromSettings(builder.build());
    TokenFilterFactory tokenFilter = analysis.tokenFilter.get("my_stop");
    assertThat(tokenFilter, instanceOf(StopTokenFilterFactory.class));
    Tokenizer tokenizer = new WhitespaceTokenizer();
    tokenizer.setReader(new StringReader("foo bar"));
    TokenStream create = tokenFilter.create(tokenizer);
    assertThat(create, instanceOf(StopFilter.class));
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:17,代码来源:StopTokenFilterTests.java

示例6: ElasticNamespaceDAO

import org.elasticsearch.common.settings.Settings.Builder; //导入方法依赖的package包/类
public ElasticNamespaceDAO(ElasticDAOConfig config) {
	try {
		Builder builder = Settings.builder();
		// Check for new hosts within the cluster
		builder.put(CLIENT_SNIFFING_CONFIG, true);
		// specify cluster name
		if (config.getClusterName() != null) {
			builder.put(CLIENT_CLUSTER_NAME_CONFIG, config.getClusterName());
		}
		Settings settings = builder.build();
		// create client
		elasticClient = new PreBuiltTransportClient(settings);
		// add hosts
		for (String elasticHost : config.getHosts()) {
			elasticClient.addTransportAddress(
					new InetSocketTransportAddress(InetAddress.getByName(elasticHost), config.getPort()));
		}
	} catch (UnknownHostException e) {
		throw new RuntimeException("Unable to initialize Eleasticsearch client " + e.getLocalizedMessage());
	}
}
 
开发者ID:carone1,项目名称:ecs-dashboard,代码行数:22,代码来源:ElasticNamespaceDAO.java

示例7: ElasticVdcDAO

import org.elasticsearch.common.settings.Settings.Builder; //导入方法依赖的package包/类
public ElasticVdcDAO(ElasticDAOConfig config) {
	try {
		Builder builder = Settings.builder();
		// Check for new hosts within the cluster
		builder.put(CLIENT_SNIFFING_CONFIG, true);
		// specify cluster name
		if (config.getClusterName() != null) {
			builder.put(CLIENT_CLUSTER_NAME_CONFIG, config.getClusterName());
		}
		Settings settings = builder.build();
		// create client
		elasticClient = new PreBuiltTransportClient(settings);
		// add hosts
		for (String elasticHost : config.getHosts()) {
			elasticClient.addTransportAddress(
					new InetSocketTransportAddress(InetAddress.getByName(elasticHost), config.getPort()));
		}
	} catch (UnknownHostException e) {
		throw new RuntimeException("Unable to initialize Eleasticsearch client " + e.getLocalizedMessage());
	}
}
 
开发者ID:carone1,项目名称:ecs-dashboard,代码行数:22,代码来源:ElasticVdcDAO.java

示例8: applySettings

import org.elasticsearch.common.settings.Settings.Builder; //导入方法依赖的package包/类
private Builder applySettings() {
    Builder settingsBuilder = Settings.builder();

    settingsBuilder.put("client.transport.ping_timeout", "15s");
    settingsBuilder.put("client.transport.nodes_sampler_interval", "5s");
    // YG: to ensure reliable connection & resolve NoNodeAvailableException
    settingsBuilder.put("client.transport.sniff", true);
    settingsBuilder.put("network.bind_host", 0);

    // YG: for supporting ES Auth with ES Shield
    Optional.ofNullable(config.getElastic().getAuth())
            .ifPresent(auth -> settingsBuilder.put("xpack.security.user", String.join(":", auth.getUser(), auth.getPwd())));

    if (Objects.nonNull(config.getElastic().getClusterName())) {
        settingsBuilder.put("cluster.name", config.getElastic().getClusterName());
    } else {
        settingsBuilder.put("client.transport.ignore_cluster_name", true);
    }
    return settingsBuilder;
}
 
开发者ID:ozlerhakan,项目名称:mongolastic,代码行数:21,代码来源:ElasticConfiguration.java

示例9: testPositionIncrementSetting

import org.elasticsearch.common.settings.Settings.Builder; //导入方法依赖的package包/类
public void testPositionIncrementSetting() throws IOException {
    Builder builder = Settings.builder().put("index.analysis.filter.my_stop.type", "stop")
            .put("index.analysis.filter.my_stop.enable_position_increments", false);
    if (random().nextBoolean()) {
        builder.put("index.analysis.filter.my_stop.version", "5.0");
    }
    builder.put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString());
    Settings settings = builder.build();
    try {
        AnalysisTestsHelper.createTestAnalysisFromSettings(settings);
        fail("Expected IllegalArgumentException");
    } catch (IllegalArgumentException e) {
        assertThat(e.getMessage(), containsString("enable_position_increments is not supported anymore"));
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:16,代码来源:StopTokenFilterTests.java

示例10: createClient

import org.elasticsearch.common.settings.Settings.Builder; //导入方法依赖的package包/类
/**
   * This method will create the client instance for elastic search.
   * @param clusterName String
   * @param host  List<String>
   * @param port List<Integer>
   * @return boolean
   * @throws Exception
   */
private static boolean createClient(String clusterName, List<String> host, List<Integer> port) throws Exception {
	Builder builder = Settings.builder();
	if (clusterName != null && !"".equals(clusterName)) {
		builder = builder.put("cluster.name", clusterName);
	}
	builder = builder.put("client.transport.sniff", true);
	builder = builder.put("client.transport.ignore_cluster_name", true);
	client = new PreBuiltTransportClient(builder.build());
	for (int i = 0; i < host.size(); i++) {
		client.addTransportAddress(
				new InetSocketTransportAddress(InetAddress.getByName(host.get(i)), ports.get(i)));
	}
	return true;
}
 
开发者ID:project-sunbird,项目名称:sunbird-utils,代码行数:23,代码来源:ConnectionManager.java

示例11: ElasticBillingDAO

import org.elasticsearch.common.settings.Settings.Builder; //导入方法依赖的package包/类
public ElasticBillingDAO(ElasticDAOConfig config) {
	
	try {
		
		Builder builder = Settings.builder();
		
		// Check for new hosts within the cluster
		builder.put(CLIENT_SNIFFING_CONFIG, true);
		
		// specify cluster name
		if( config.getClusterName() != null ) {
			builder.put(CLIENT_CLUSTER_NAME_CONFIG, config.getClusterName());
		}
		
		Settings settings = builder.build();
		
		// create client
		elasticClient = new PreBuiltTransportClient(settings);
		
		// add hosts
		for( String elasticHost : config.getHosts()) {
			elasticClient.addTransportAddress(
					new InetSocketTransportAddress(InetAddress.getByName(elasticHost), config.getPort()));				
		}
		
	} catch (UnknownHostException e) {
		throw new RuntimeException("Unable to initialize Eleasticsearch client " + e.getLocalizedMessage() );
	}				
}
 
开发者ID:carone1,项目名称:ecs-dashboard,代码行数:30,代码来源:ElasticBillingDAO.java

示例12: startElasticNode

import org.elasticsearch.common.settings.Settings.Builder; //导入方法依赖的package包/类
private void startElasticNode() throws InterruptedException, ExecutionException, IOException {

		Builder builder = Settings.builder()//
				.put("node.master", true)//
				.put("node.data", true)//
				.put("cluster.name", CLUSTER_NAME)//
				// disable automatic index creation
				.put("action.auto_create_index", false)//
				// disable dynamic indexing
				.put("index.mapper.dynamic", false)//
				// disable rebalance to avoid automatic rebalance
				// when a temporary second node appears
				.put("cluster.routing.rebalance.enable", "none")//
				.put("http.enabled", //
						config.isElasticHttpEnabled())//
				.put("network.host", //
						config.elasticNetworkHost())//
				.put("path.home", //
						config.homePath().toAbsolutePath().toString())
				.put("path.data", //
						config.elasticDataPath().toAbsolutePath().toString());

		if (config.snapshotsPath().isPresent())
			builder.put("path.repo", //
					config.snapshotsPath().get().toAbsolutePath().toString());

		elasticNode = new ElasticNode(builder.build(), //
				DeleteByQueryPlugin.class, //
				CloudAwsPlugin.class);

		elasticNode.start();
		setElasticClient(elasticNode.client());

		// wait for cluster to fully initialize and turn asynchronously from
		// RED status to GREEN before to initialize anything else
		// wait for 60 seconds maximum
		elastic.ensureAllIndicesGreen();
	}
 
开发者ID:spacedog-io,项目名称:spacedog-server,代码行数:39,代码来源:Start.java

示例13: getRandomNodeSettings

import org.elasticsearch.common.settings.Settings.Builder; //导入方法依赖的package包/类
private Settings getRandomNodeSettings(long seed) {
    Random random = new Random(seed);
    Builder builder = Settings.builder();
    builder.put(Transport.TRANSPORT_TCP_COMPRESS.getKey(), rarely(random));
    if (random.nextBoolean()) {
        builder.put("cache.recycler.page.type", RandomPicks.randomFrom(random, PageCacheRecycler.Type.values()));
    }
    if (random.nextInt(10) == 0) { // 10% of the nodes have a very frequent check interval
        builder.put(SearchService.KEEPALIVE_INTERVAL_SETTING.getKey(), TimeValue.timeValueMillis(10 + random.nextInt(2000)).getStringRep());
    } else if (random.nextInt(10) != 0) { // 90% of the time - 10% of the time we don't set anything
        builder.put(SearchService.KEEPALIVE_INTERVAL_SETTING.getKey(), TimeValue.timeValueSeconds(10 + random.nextInt(5 * 60)).getStringRep());
    }
    if (random.nextBoolean()) { // sometimes set a
        builder.put(SearchService.DEFAULT_KEEPALIVE_SETTING.getKey(), TimeValue.timeValueSeconds(100 + random.nextInt(5 * 60)).getStringRep());
    }

    builder.put(EsExecutors.PROCESSORS_SETTING.getKey(), 1 + random.nextInt(3));
    if (random.nextBoolean()) {
        if (random.nextBoolean()) {
            builder.put("indices.fielddata.cache.size", 1 + random.nextInt(1000), ByteSizeUnit.MB);
        }
    }

    // randomize tcp settings
    if (random.nextBoolean()) {
        builder.put(TcpTransport.CONNECTIONS_PER_NODE_RECOVERY.getKey(), random.nextInt(2) + 1);
        builder.put(TcpTransport.CONNECTIONS_PER_NODE_BULK.getKey(), random.nextInt(3) + 1);
        builder.put(TcpTransport.CONNECTIONS_PER_NODE_REG.getKey(), random.nextInt(6) + 1);
    }

    if (random.nextBoolean()) {
        builder.put(MappingUpdatedAction.INDICES_MAPPING_DYNAMIC_TIMEOUT_SETTING.getKey(), new TimeValue(RandomNumbers.randomIntBetween(random, 10, 30), TimeUnit.SECONDS));
    }

    if (random.nextInt(10) == 0) {
        builder.put(HierarchyCircuitBreakerService.REQUEST_CIRCUIT_BREAKER_TYPE_SETTING.getKey(), "noop");
        builder.put(HierarchyCircuitBreakerService.FIELDDATA_CIRCUIT_BREAKER_TYPE_SETTING.getKey(), "noop");
    }

    if (random.nextBoolean()) {
        if (random.nextInt(10) == 0) { // do something crazy slow here
            builder.put(RecoverySettings.INDICES_RECOVERY_MAX_BYTES_PER_SEC_SETTING.getKey(), new ByteSizeValue(RandomNumbers.randomIntBetween(random, 1, 10), ByteSizeUnit.MB));
        } else {
            builder.put(RecoverySettings.INDICES_RECOVERY_MAX_BYTES_PER_SEC_SETTING.getKey(), new ByteSizeValue(RandomNumbers.randomIntBetween(random, 10, 200), ByteSizeUnit.MB));
        }
    }

    if (random.nextBoolean()) {
        builder.put(TcpTransport.PING_SCHEDULE.getKey(), RandomNumbers.randomIntBetween(random, 100, 2000) + "ms");
    }

    if (random.nextBoolean()) {
        builder.put(ScriptService.SCRIPT_CACHE_SIZE_SETTING.getKey(), RandomNumbers.randomIntBetween(random, 0, 2000));
    }
    if (random.nextBoolean()) {
        builder.put(ScriptService.SCRIPT_CACHE_EXPIRE_SETTING.getKey(), TimeValue.timeValueMillis(RandomNumbers.randomIntBetween(random, 750, 10000000)).getStringRep());
    }

    return builder.build();
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:61,代码来源:InternalTestCluster.java

示例14: testMoreDocs

import org.elasticsearch.common.settings.Settings.Builder; //导入方法依赖的package包/类
public void testMoreDocs() throws Exception {
    Builder builder = Settings.builder();
    builder.put("index.analysis.analyzer.synonym.tokenizer", "whitespace");
    builder.putArray("index.analysis.analyzer.synonym.filter", "synonym", "lowercase");
    builder.put("index.analysis.filter.synonym.type", "synonym");
    builder.putArray("index.analysis.filter.synonym.synonyms", "ave => ave, avenue", "street => str, street");

    XContentBuilder mapping = XContentFactory.jsonBuilder().startObject().startObject("type1").startObject("properties")
            .startObject("field1").field("type", "text").field("analyzer", "whitespace").field("search_analyzer", "synonym")
            .endObject().endObject().endObject().endObject();

    assertAcked(client().admin().indices().prepareCreate("test").addMapping("type1", mapping)
            .setSettings(builder.put("index.number_of_shards", 1)));

    client().prepareIndex("test", "type1", "1").setSource("field1", "massachusetts avenue boston massachusetts").execute().actionGet();
    client().prepareIndex("test", "type1", "2").setSource("field1", "lexington avenue boston massachusetts").execute().actionGet();
    client().prepareIndex("test", "type1", "3").setSource("field1", "boston avenue lexington massachusetts").execute().actionGet();
    client().admin().indices().prepareRefresh("test").execute().actionGet();
    client().prepareIndex("test", "type1", "4").setSource("field1", "boston road lexington massachusetts").execute().actionGet();
    client().prepareIndex("test", "type1", "5").setSource("field1", "lexington street lexington massachusetts").execute().actionGet();
    client().prepareIndex("test", "type1", "6").setSource("field1", "massachusetts avenue lexington massachusetts").execute()
            .actionGet();
    client().prepareIndex("test", "type1", "7").setSource("field1", "bosten street san franciso california").execute().actionGet();
    client().admin().indices().prepareRefresh("test").execute().actionGet();
    client().prepareIndex("test", "type1", "8").setSource("field1", "hollywood boulevard los angeles california").execute().actionGet();
    client().prepareIndex("test", "type1", "9").setSource("field1", "1st street boston massachussetts").execute().actionGet();
    client().prepareIndex("test", "type1", "10").setSource("field1", "1st street boston massachusetts").execute().actionGet();
    client().admin().indices().prepareRefresh("test").execute().actionGet();
    client().prepareIndex("test", "type1", "11").setSource("field1", "2st street boston massachusetts").execute().actionGet();
    client().prepareIndex("test", "type1", "12").setSource("field1", "3st street boston massachusetts").execute().actionGet();
    client().admin().indices().prepareRefresh("test").execute().actionGet();
    SearchResponse searchResponse = client()
            .prepareSearch()
            .setQuery(QueryBuilders.matchQuery("field1", "lexington avenue massachusetts").operator(Operator.OR))
            .setFrom(0)
            .setSize(5)
            .setRescorer(queryRescorer(QueryBuilders.matchPhraseQuery("field1", "lexington avenue massachusetts").slop(3))
                            .setQueryWeight(0.6f).setRescoreQueryWeight(2.0f), 20).execute().actionGet();

    assertThat(searchResponse.getHits().getHits().length, equalTo(5));
    assertHitCount(searchResponse, 9);
    assertFirstHit(searchResponse, hasId("2"));
    assertSecondHit(searchResponse, hasId("6"));
    assertThirdHit(searchResponse, hasId("3"));

    searchResponse = client()
            .prepareSearch()
            .setQuery(QueryBuilders.matchQuery("field1", "lexington avenue massachusetts").operator(Operator.OR))
            .setFrom(0)
            .setSize(5)
            .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
            .setRescorer(queryRescorer(QueryBuilders.matchPhraseQuery("field1", "lexington avenue massachusetts").slop(3))
                            .setQueryWeight(0.6f).setRescoreQueryWeight(2.0f), 20).execute().actionGet();

    assertThat(searchResponse.getHits().getHits().length, equalTo(5));
    assertHitCount(searchResponse, 9);
    assertThat(searchResponse.getHits().getMaxScore(), equalTo(searchResponse.getHits().getHits()[0].getScore()));
    assertFirstHit(searchResponse, hasId("2"));
    assertSecondHit(searchResponse, hasId("6"));
    assertThirdHit(searchResponse, hasId("3"));

    // Make sure non-zero from works:
    searchResponse = client()
            .prepareSearch()
            .setQuery(QueryBuilders.matchQuery("field1", "lexington avenue massachusetts").operator(Operator.OR))
            .setFrom(2)
            .setSize(5)
            .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
            .setRescorer(queryRescorer(QueryBuilders.matchPhraseQuery("field1", "lexington avenue massachusetts").slop(3))
                            .setQueryWeight(0.6f).setRescoreQueryWeight(2.0f), 20).execute().actionGet();

    assertThat(searchResponse.getHits().getHits().length, equalTo(5));
    assertHitCount(searchResponse, 9);
    assertThat(searchResponse.getHits().getMaxScore(), greaterThan(searchResponse.getHits().getHits()[0].getScore()));
    assertFirstHit(searchResponse, hasId("3"));
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:77,代码来源:QueryRescorerIT.java

示例15: testSmallRescoreWindow

import org.elasticsearch.common.settings.Settings.Builder; //导入方法依赖的package包/类
public void testSmallRescoreWindow() throws Exception {
    Builder builder = Settings.builder();
    builder.put("index.analysis.analyzer.synonym.tokenizer", "whitespace");
    builder.putArray("index.analysis.analyzer.synonym.filter", "synonym", "lowercase");
    builder.put("index.analysis.filter.synonym.type", "synonym");
    builder.putArray("index.analysis.filter.synonym.synonyms", "ave => ave, avenue", "street => str, street");

    XContentBuilder mapping = XContentFactory.jsonBuilder().startObject().startObject("type1").startObject("properties")
            .startObject("field1").field("type", "text").field("analyzer", "whitespace").field("search_analyzer", "synonym")
            .endObject().endObject().endObject().endObject();

    assertAcked(client().admin().indices().prepareCreate("test").addMapping("type1", mapping)
            .setSettings(builder.put("index.number_of_shards", 1)));

    client().prepareIndex("test", "type1", "3").setSource("field1", "massachusetts").execute().actionGet();
    client().prepareIndex("test", "type1", "6").setSource("field1", "massachusetts avenue lexington massachusetts").execute()
            .actionGet();
    client().admin().indices().prepareRefresh("test").execute().actionGet();
    client().prepareIndex("test", "type1", "1").setSource("field1", "lexington massachusetts avenue").execute().actionGet();
    client().prepareIndex("test", "type1", "2").setSource("field1", "lexington avenue boston massachusetts road").execute().actionGet();
    client().admin().indices().prepareRefresh("test").execute().actionGet();

    SearchResponse searchResponse = client()
            .prepareSearch()
            .setQuery(QueryBuilders.matchQuery("field1", "massachusetts"))
            .setFrom(0)
        .setSize(5).execute().actionGet();
    assertThat(searchResponse.getHits().getHits().length, equalTo(4));
    assertHitCount(searchResponse, 4);
    assertThat(searchResponse.getHits().getMaxScore(), equalTo(searchResponse.getHits().getHits()[0].getScore()));
    assertFirstHit(searchResponse, hasId("3"));
    assertSecondHit(searchResponse, hasId("6"));
    assertThirdHit(searchResponse, hasId("1"));
    assertFourthHit(searchResponse, hasId("2"));

    // Now, rescore only top 2 hits w/ proximity:
    searchResponse = client()
            .prepareSearch()
            .setQuery(QueryBuilders.matchQuery("field1", "massachusetts"))
            .setFrom(0)
            .setSize(5)
            .setRescorer(queryRescorer(QueryBuilders.matchPhraseQuery("field1", "lexington avenue massachusetts").slop(3))
                            .setQueryWeight(0.6f).setRescoreQueryWeight(2.0f), 2).execute().actionGet();
    // Only top 2 hits were re-ordered:
    assertThat(searchResponse.getHits().getHits().length, equalTo(4));
    assertHitCount(searchResponse, 4);
    assertThat(searchResponse.getHits().getMaxScore(), equalTo(searchResponse.getHits().getHits()[0].getScore()));
    assertFirstHit(searchResponse, hasId("6"));
    assertSecondHit(searchResponse, hasId("3"));
    assertThirdHit(searchResponse, hasId("1"));
    assertFourthHit(searchResponse, hasId("2"));

    // Now, rescore only top 3 hits w/ proximity:
    searchResponse = client()
            .prepareSearch()
            .setQuery(QueryBuilders.matchQuery("field1", "massachusetts"))
            .setFrom(0)
            .setSize(5)
            .setRescorer(queryRescorer(QueryBuilders.matchPhraseQuery("field1", "lexington avenue massachusetts").slop(3))
                            .setQueryWeight(0.6f).setRescoreQueryWeight(2.0f), 3).execute().actionGet();

    // Only top 3 hits were re-ordered:
    assertThat(searchResponse.getHits().getHits().length, equalTo(4));
    assertHitCount(searchResponse, 4);
    assertThat(searchResponse.getHits().getMaxScore(), equalTo(searchResponse.getHits().getHits()[0].getScore()));
    assertFirstHit(searchResponse, hasId("6"));
    assertSecondHit(searchResponse, hasId("1"));
    assertThirdHit(searchResponse, hasId("3"));
    assertFourthHit(searchResponse, hasId("2"));
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:71,代码来源:QueryRescorerIT.java


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