elasticsearch 实例大全

本文提供了多个使用 org.elasticsearch.node.NodeBuilder 的示例代码片段,这些示例来自不同的开源项目,展示了如何配置 Elasticsearch 节点设置并启动节点。

java Code Examples for org.elasticsearch.node.NodeBuilder

The following are top voted examples for showing how to use org.elasticsearch.node.NodeBuilder. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples. 

+ Save this class to your library

Example 1

Project: vertexium   File: ElasticsearchSingleDocumentSearchIndexTestBase.java View source codeVote up9 votes
@BeforeClass
public static void beforeClass() throws Exception {
    tempDir = File.createTempFile("elasticsearch-temp", Long.toString(System.nanoTime()));
    tempDir.delete();
    tempDir.mkdir();
    LOGGER.info("writing to: %s", tempDir);

    clusterName = UUID.randomUUID().toString();
    elasticSearchNode = NodeBuilder
            .nodeBuilder()
            .local(false)
            .clusterName(clusterName)
            .settings(
                    ImmutableSettings.settingsBuilder()
                            .put("script.disable_dynamic", "false")
                            .put("gateway.type", "local")
                            .put("index.number_of_shards", "1")
                            .put("index.number_of_replicas", "0")
                            .put("path.data", new File(tempDir, "data").getAbsolutePath())
                            .put("path.logs", new File(tempDir, "logs").getAbsolutePath())
                            .put("path.work", new File(tempDir, "work").getAbsolutePath())
            ).node();
    elasticSearchNode.start();
}

Example 2

Project: search-guard   File: AbstractUnitTest.java View source codeVote up6 votes
public final void startES(final Settings settings) throws Exception {

        FileUtils.deleteDirectory(new File("data"));

        Set<Integer> ports = null;
        int offset = 0;
        final int windowsSize = 12;
        do {
            ports = AvailablePortFinder.getAvailablePorts(AvailablePortFinder.MAX_PORT_NUMBER - offset - windowsSize,
                    AvailablePortFinder.MAX_PORT_NUMBER - offset);
            offset += windowsSize;
        } while (ports.size() < 7);

        final Iterator<Integer> portIt = ports.iterator();

        elasticsearchHttpPort1 = portIt.next();
        elasticsearchHttpPort2 = portIt.next();
        elasticsearchHttpPort3 = portIt.next();

        elasticsearchNodePort1 = portIt.next();
        elasticsearchNodePort2 = portIt.next();
        elasticsearchNodePort3 = portIt.next();

        esNode1 = new NodeBuilder().settings(
                getDefaultSettingsBuilder(1, elasticsearchNodePort1, elasticsearchHttpPort1, false, true).put(
                        settings == null ? ImmutableSettings.Builder.EMPTY_SETTINGS : settings).build()).node();
        esNode2 = new NodeBuilder().settings(
                getDefaultSettingsBuilder(2, elasticsearchNodePort2, elasticsearchHttpPort2, true, true).put(
                        settings == null ? ImmutableSettings.Builder.EMPTY_SETTINGS : settings).build()).node();
        esNode3 = new NodeBuilder().settings(
                getDefaultSettingsBuilder(3, elasticsearchNodePort3, elasticsearchHttpPort3, true, false).put(
                        settings == null ? ImmutableSettings.Builder.EMPTY_SETTINGS : settings).build()).node();

        waitForGreenClusterState(esNode1.client());
    }

 

Example 3

Project: uima-elasticsearch   File: ESWriter.java View source codeVote up6 votes
@Override
public void initialize(UimaContext context)
	throws ResourceInitializationException {
	super.initialize(context);

	try {
		serializer = CasSerializerMetaFactory.Instance().getFactory(
			serializerFactoryName).createSerializer();
	} catch (UimaSerializationBaseException e) {
		throw new ResourceInitializationException(e);
	}

	node = NodeBuilder.nodeBuilder().node();
	client = node.client();
}

Example 4

Project: elasticsearch-hadoop   File: EsEmbeddedServer.java View source codeVote up6 votes
public EsEmbeddedServer(String clusterName, String homePath, String dataPath, String httpRange, String transportRange, boolean hasSlave) {
    Properties props = new Properties();
    props.setProperty("path.home", homePath);
    props.setProperty("path.data", dataPath);
    props.setProperty("http.port", httpRange);
    props.setProperty("transport.tcp.port", transportRange);
    props.setProperty("cluster.name", "es.hadoop.test");
    props.setProperty("node.local", "true");
    //props.setProperty("es.index.store.type", "memory");
    // props.setProperty("gateway.type", "none");
    if (!hasSlave) {
        props.setProperty("discovery.zen.ping.multicast", "false");
        props.setProperty("discovery.zen.ping.multicast.enabled", "false");
    }
    //props.setProperty("script.disable_dynamic", "false");
    props.setProperty("script.inline", "on");
    props.setProperty("script.indexed", "on");

    Settings settings = Settings.settingsBuilder().put(props).build();
    node = NodeBuilder.nodeBuilder().local(false).client(false).settings(settings).clusterName(clusterName).build();
}

 

Example 5

Project: elassandra   File: TribeService.java View source codeVote up6 votes
@Inject
public TribeService(Settings settings, ClusterService clusterService, DiscoveryService discoveryService) {
    super(settings);
    this.clusterService = clusterService;
    Map<String, Settings> nodesSettings = Maps.newHashMap(settings.getGroups("tribe", true));
    nodesSettings.remove("blocks"); // remove prefix settings that don't indicate a client
    nodesSettings.remove("on_conflict"); // remove prefix settings that don't indicate a client
    for (Map.Entry<String, Settings> entry : nodesSettings.entrySet()) {
        ImmutableSettings.Builder sb = ImmutableSettings.builder().put(entry.getValue());
        sb.put("node.name", settings.get("name") + "/" + entry.getKey());
        sb.put(TRIBE_NAME, entry.getKey());
        sb.put("config.ignore_system_properties", true);
        if (sb.get("http.enabled") == null) {
            sb.put("http.enabled", false);
        }
        nodes.add((InternalNode) NodeBuilder.nodeBuilder().settings(sb).client(true).loadConfigSettings(false).build());
    }

    String[] blockIndicesWrite = Strings.EMPTY_ARRAY;
    String[] blockIndicesRead = Strings.EMPTY_ARRAY;
    String[] blockIndicesMetadata = Strings.EMPTY_ARRAY;
    if (!nodes.isEmpty()) {
        // remove the initial election / recovery blocks since we are not going to have a
        // master elected in this single tribe  node local "cluster"
        clusterService.removeInitialStateBlock(discoveryService.getNoMasterBlock());
        clusterService.removeInitialStateBlock(GatewayService.STATE_NOT_RECOVERED_BLOCK);
        if (settings.getAsBoolean("tribe.blocks.write", false)) {
            clusterService.addInitialStateBlock(TRIBE_WRITE_BLOCK);
        }
        blockIndicesWrite = settings.getAsArray("tribe.blocks.write.indices", Strings.EMPTY_ARRAY);
        if (settings.getAsBoolean("tribe.blocks.metadata", false)) {
            clusterService.addInitialStateBlock(TRIBE_METADATA_BLOCK);
        }
        blockIndicesMetadata = settings.getAsArray("tribe.blocks.metadata.indices", Strings.EMPTY_ARRAY);
        blockIndicesRead = settings.getAsArray("tribe.blocks.read.indices", Strings.EMPTY_ARRAY);
        for (InternalNode node : nodes) {
            node.injector().getInstance(ClusterService.class).add(new TribeClusterStateListener(node));
        }
    }
    this.blockIndicesMetadata = blockIndicesMetadata;
    this.blockIndicesRead = blockIndicesRead;
    this.blockIndicesWrite = blockIndicesWrite;

    this.onConflict = settings.get("tribe.on_conflict", ON_CONFLICT_ANY);
}

Example 6

Project: crate   File: SQLServiceTest.java View source codeVote up6 votes
@Test
public void testDisableAndReEnable() throws Exception {
    InternalNode node = (InternalNode) NodeBuilder.nodeBuilder().local(true).data(true).settings(
            ImmutableSettings.builder()
                    .put(ClusterName.SETTING, getClass().getName())
                    .put("node.name", getClass().getName())
                    .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1)
                    .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 0)
                    .put(EsExecutors.PROCESSORS, 1)
                    .put("http.enabled", false)
                    .put("index.store.type", "ram")
                    .put("config.ignore_system_properties", true)
                    .put("gateway.type", "none")).build();
    node.start();


    SQLService sqlService = node.injector().getInstance(SQLService.class);
    TransportSQLAction transportSQLAction = node.injector().getInstance(TransportSQLAction.class);
    transportSQLAction.execute(new SQLRequest("select name from sys.cluster")).actionGet();

    sqlService.disable();

    try {
        transportSQLAction.execute(new SQLRequest("select name from sys.cluster")).actionGet();
        fail("no exception thrown");
    } catch (NodeDisconnectedException e) {
        // success!
    }

    sqlService.start();
    transportSQLAction.execute(new SQLRequest("select name from sys.cluster")).actionGet();

    node.close();
}

Example 7

Project: dev-search   File: EmbeddedRunnerMain.java View source codeVote up6 votes
private void start(String[] args) {
        displayBanner();
        Node node = null;
        try {
            if (args.length < 1) {
                throw new RuntimeException("Need more args. First is data dir");
            }
            Path dataPath = new File(args[0]).toPath();
            Files.createDirectories(dataPath);
            if (args.length > 1) {
                monitorHeartBeat(Integer.parseInt(args[1]));
            }
            NodeBuilder nodeBuilder = nodeBuilder();
//            String host = "btsm01p:9300";
            String pluginDir = findPluginPath();
//            System.getProperty("user.home")

            System.out.println("Using data dir " + dataPath);

            int httpPort = 9200;
            nodeBuilder.settings()
                    .put("path.plugins", pluginDir)
                    .put("path.data", dataPath.toString())
                    .put("http.port", httpPort)
                    .put("transport.tcp.port", 9300)
                    .put("discovery.zen.ping.multicast.enabled", "false");
//                    .put("discovery.zen.ping.unicast.hosts", host);

            //node = nodeBuilder.clusterName("elasticsearch").client(true).node();
            node = nodeBuilder.clusterName("elasticsearch").node();
            addShutdownHook(nodeAsClosable(node), "Node");
            String baseUrl = "http://localhost:" + httpPort;
            initializeClient(baseUrl);
            Thread.sleep(2000);
            System.out.println("Now navigate to " + baseUrl + "/_plugin/dev-search/ to test");

            Thread.sleep(Integer.MAX_VALUE);
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            try {
                node.close();
            } catch (Exception e) { }
        }

        System.exit(1);
    }

Example 8

Project: rtgov   File: ElasticsearchNodeImpl.java View source codeVote up6 votes
/**
 * This method initializes the node.
 */
protected void initNode() {
    /**
     * quick fix for integration tests. if hosts property set to "embedded" then a local node is start.
     * maven dependencies need to be defined correctly for this to work
     */
    ClassLoader cl = Thread.currentThread().getContextClassLoader();

    try {
        // Need to use the classloader for Elasticsearch to pick up the property files when
        // running in an OSGi environment            
        Thread.currentThread().setContextClassLoader(TransportClient.class.getClassLoader());
        
        Properties defaultProps=new ElasticsearchPropertyProvider().getProperties();

        _node = NodeBuilder.nodeBuilder()
                .settings(ImmutableSettings.settingsBuilder()
                .put(defaultProps)).node();

        _node.start(); 
        _client = _node.client();
    } finally {
        Thread.currentThread().setContextClassLoader(cl);
    }
    
    if (LOG.isLoggable(Level.FINEST)) {
        LOG.finest("Initialized Elasticsearch node="+_node+" client="+_client);
    }
}

Example 9

Project: swagger-for-elasticsearch   File: ElasticsearchServer.java View source codeVote up6 votes
public ElasticsearchServer() {
    node = NodeBuilder.nodeBuilder().settings(
        Settings.settingsBuilder()
            .put("http.port", 9201)
            .put("node.name", "swagger-for-elasticsearch-test-node")
            .put("cluster.name", "swagger-for-elasticsearch-test-cluster")
            .put("path.data", HOME_DIRECTORY)
            .put("path.home", DATA_DIRECTORY)
    ).node();
}

Example 10

Project: elasticsearch-plugin-bundle   File: ReferenceMappingTests.java View source codeVote up6 votes
@BeforeClass
public static void setupMapperParser() throws IOException {
    Settings nodeSettings = Settings.settingsBuilder()
            .put("path.home", System.getProperty("path.home"))
            .put("plugin.types", BundlePlugin.class.getName())
            .put("index.number_of_shards", 1)
            .put("index.number_of_replica", 0)
            .build();
    node = NodeBuilder.nodeBuilder().settings(nodeSettings).local(true).build().start();
    client = node.client();
    try {
        client.admin().indices().prepareDelete("test").execute().actionGet();
    } catch (Exception e) {
        logger.warn("unable to delete test index");
    }
    BytesReference json = jsonBuilder().startObject().array("myfield", "a","b","c").endObject().bytes();
    client.prepareIndex("test", "test", "1234").setSource(json).execute().actionGet();
    try {
        client.admin().indices().prepareDelete("authorities").execute().actionGet();
    } catch (Exception e) {
        logger.warn("unable to delete test index");
    }

    json = jsonBuilder().startObject().field("author", "John Doe").endObject().bytes();
    client.prepareIndex("authorities", "persons", "1").setSource(json).execute().actionGet();

    mapperParser = MapperTestUtils.newMapperParser();
    mapperParser.putTypeParser(ReferenceMapper.CONTENT_TYPE, new ReferenceMapper.TypeParser(client));
}

Example 11

Project: esi4j   File: TestUtils.java View source codeVote up6 votes
public static Esi4JClient newClient(String clusterName) {

		if (StringUtils.empty(clusterName)) {
			clusterName = ClusterName.DEFAULT.value();
		}

		final File tmp = newTmpDir();
		Settings settings = nodeSettings(tmp).put("cluster.name", clusterName).build();

		Node node = NodeBuilder.nodeBuilder().settings(settings).build();

		return new NodeClient(clusterName, node) {
			@Override
			public void close() {
				super.close();
				FileUtils.delete(tmp);
			}

		};
	}

Example 12

Project: camunda-bpm-elasticsearch   File: ElasticSearchClient.java View source codeVote up6 votes
protected Client init() {
    Client client = null;

    ImmutableSettings.Builder settingsBuilder = ImmutableSettings.builder()
        .put("cluster.name", historyPluginConfiguration.getEsClusterName());

    if (historyPluginConfiguration.isTransportClient()) {
      // sniff for rest of cluster settingsBuilder.put("client.transport.sniff", true);
      addCustomESProperties(settingsBuilder, historyPluginConfiguration.getProperties());

      TransportClient transportClient = new TransportClient(settingsBuilder).addTransportAddress(
          new InetSocketTransportAddress(historyPluginConfiguration.getEsHost(), Integer.parseInt(historyPluginConfiguration.getEsPort())));
      LOGGER.info("Successfully connected to " + transportClient.connectedNodes());
      client = transportClient;
    } else {
      if (esNode == null) {
        // initialize default settings
        settingsBuilder
            .put("node.name", "rocking-camunda-bpm-history")
            .put("node.client", true) // make node a client, so it won't become a master
            .put("node.local", false)
            .put("node.data", false)
            .put("node.http.enabled", true);
//            .put("discovery.zen.ping.multicast.enabled", false)
//            .put("discovery.zen.ping.unicast.hosts", "127.0.0.1:9300");

        addCustomESProperties(settingsBuilder, historyPluginConfiguration.getProperties());

        esNode = NodeBuilder.nodeBuilder()
            .loadConfigSettings(true)
            .settings(settingsBuilder)
            .build();

        if (LOGGER.isLoggable(Level.INFO)) {
          LOGGER.info("Initialized node with settings: " + esNode.settings().getAsMap().toString());
        }

        esNode.start();
      }

      client = esNode.client();
    }

    return client;
  }

Example 13

Project: nuxeo   File: BareElasticSearchFeature.java View source codeVote up6 votes
@Override
public void start(FeaturesRunner runner) throws Exception {

    File home = Framework.getRuntime().getHome();
    File esDirectory = new File(home, "elasticsearch");
    if (!esDirectory.exists() && !esDirectory.mkdir()) {
        throw new InvalidParameterException("Can not create directory: " + esDirectory.getAbsolutePath());
    }
    Settings settings = ImmutableSettings.settingsBuilder().put("node.http.enabled", true).put("path.logs",
            esDirectory.getPath() + "/logs").put("path.data", esDirectory.getPath() + "/data").put("gateway.type",
            "none").put("index.store.type", "memory").put("index.number_of_shards", 1).put(
            "index.number_of_replicas", 1).build();
    node = NodeBuilder.nodeBuilder().local(true).settings(settings).node();
    client = node.client();
    super.start(runner);
}

Example 14

Project: elasticsearch-reindex-tool   File: EmbeddedElasticsearchCluster.java View source codeVote up6 votes
private EmbeddedElasticsearchCluster(String clusterName, int apiPort) {
  NodeBuilder nodeBuilder = nodeBuilder()
      .clusterName(clusterName)
      .data(true);
  ImmutableSettings.Builder settings = nodeBuilder.settings()
      .put("http.port", ELS_PORT)
      .put("index.store.type", "memory")
      .put("transport.tcp.port", apiPort);

  dataNode = nodeBuilder.settings(settings).node();
  dataNode.client().admin().cluster().prepareHealth().setWaitForGreenStatus().get();
}

Example 15

Project: datacollector   File: TestElasticSearchTarget.java View source codeVote up6 votes
@BeforeClass
public static void setUp() throws Exception {
  File esDir = new File("target", UUID.randomUUID().toString());
  esPort = getRandomPort();
  Assert.assertTrue(esDir.mkdirs());
  ImmutableSettings.Builder settings = ImmutableSettings.builder();
  settings.put("cluster.name", esName);
  settings.put("http.enabled", false);
  settings.put("transport.tcp.port", esPort);
  settings.put("path.conf", esDir.getAbsolutePath());
  settings.put("path.data", esDir.getAbsolutePath());
  settings.put("path.logs", esDir.getAbsolutePath());
  settings.put("plugins." + PluginsService.LOAD_PLUGIN_FROM_CLASSPATH, false);
  esServer = NodeBuilder.nodeBuilder().settings(settings.build()).build();
  esServer.start();
}

Example 16

Project: elasticsearch-maven-plugin   File: ElasticsearchNode.java View source codeVote up6 votes
/**
 * Start a local ES node with the given settings.
 * <br>
 * If the local node is already running prior to calling this method,
 * an IllegalStateException will be thrown.
 * @param settings
 * @throws MojoExecutionException 
 */
public ElasticsearchNode(Settings settings) throws MojoExecutionException
{
    // Set the node to be as lightweight as possible,
    // at the same time being able to be discovered from an external JVM.
    settings = ImmutableSettings.settingsBuilder()
            .put("index.number_of_shards", 1)
            .put("index.number_of_replicas", 0)
            .put("network.host", "127.0.0.1")
            .put("discovery.zen.ping.timeout", "3ms")
            .put("discovery.zen.ping.multicast.enabled", false)
            .put("http.cors.enabled", true)
            .put(settings)
            .build();
    
    httpPort = settings.getAsInt("http.port", 9200);
    
    node = NodeBuilder.nodeBuilder().settings(settings).node();
}

Example 17

Project: querydsl-contrib   File: ElasticsearchQueryTest.java View source codeVote up6 votes
@BeforeClass
public static void beforeClass() {
    ImmutableSettings.Builder settings = ImmutableSettings.builder().put("path.data", ElasticsearchQueryTest.class.getResource("").getPath());
    Node node = NodeBuilder.nodeBuilder().local(true).settings(settings).node();
    client = node.client();

}

Example 18

Project: weblounge   File: SearchIndex.java View source codeVote up6 votes
/**
 * Initializes an Elasticsearch node for the site.
 * 
 * @throws Exception
 *           if loading or creating solr fails
 */
private void init() throws Exception {
  synchronized (this) {
    if (elasticSearch == null) {
      logger.info("Starting local Elasticsearch node");

      // Prepare the configuration of the elastic search node
      Settings settings = loadSettings();

      // Configure and start the elastic search node. In a testing scenario,
      // the
      // node is being created locally.
      NodeBuilder nodeBuilder = NodeBuilder.nodeBuilder().settings(settings);
      elasticSearch = nodeBuilder.local(TestUtils.isTest()).build();
      elasticSearch.start();
    }
  }
  
  // Create the client
  synchronized (elasticSearch) {
    nodeClient = elasticSearch.client();
    elasticSearchClients.add(nodeClient);
  }
  
  // Create indices and type definitions
  createIndices();
}

Example 19

Project: metrics   File: ElasticSearchHostRepository.java View source codeVote up5 votes
/**
 * {@inheritDoc}
 */
@Override
public void open() {
    assertIsOpen(false);
    LOGGER.debug().setMessage("Opening host repository").log();

    // Initialize Elastic Search
    _node = new NodeBuilder()
            .loadConfigSettings(false)
            .settings(_settings)
            .build();
    _node.start();

    _client = _node.client();
    _client.admin().cluster().prepareHealth().setWaitForGreenStatus().execute().actionGet();

    final ClusterStateResponse response = _client.admin().cluster().prepareState().execute().actionGet();
    final boolean hasIndex = response.getState().metaData().hasIndex(INDEX);
    if (!hasIndex) {
        _client.admin().indices().create(
                Requests.createIndexRequest(INDEX)
                        .settings(_indexSettings)
                        .mapping(
                                TYPE,
                                "{\n"
                                        + "    \"properties\" : {\n"
                                        + "        \"hostname\" : {\n"
                                        + "            \"type\" : \"string\",\n"
                                        + "            \"store\" : true,\n"
                                        + "            \"fields\": {\n"
                                        + "                \"raw\": {\n"
                                        + "                    \"type\":  \"string\",\n"
                                        + "                    \"index\": \"not_analyzed\"\n"
                                        + "                }\n"
                                        + "            }\n"
                                        + "        },\n"
                                        + "        \"metricsSoftwareState\" : {\n"
                                        + "            \"type\" : \"string\", \n"
                                        + "            \"store\" : true\n"
                                        + "        },\n"
                                        + "        \"cluster\" : {\n"
                                        + "            \"type\" : \"string\",\n"
                                        + "            \"store\": true\n"
                                        + "        }\n"
                                        + "    }\n"
                                        + "}")
                        ).actionGet();

        _client.admin().cluster().health(new ClusterHealthRequest(INDEX).waitForGreenStatus()).actionGet();
    }

    _isOpen.set(true);
    LOGGER.info().setMessage("ElasticSearchHostRepository up and healthy").log();
}

Example 20

Project: titan   File: ElasticSearchIndex.java View source codeVote up5 votes
public ElasticSearchIndex(Configuration config) {
    indexName = config.getString(INDEX_NAME_KEY, INDEX_NAME_DEFAULT);

    checkExpectedClientVersion();

    if (!config.containsKey(GraphDatabaseConfiguration.HOSTNAME_KEY)) {
        boolean clientOnly = config.getBoolean(CLIENT_ONLY_KEY, CLIENT_ONLY_DEFAULT);
        boolean local = config.getBoolean(LOCAL_MODE_KEY, LOCAL_MODE_DEFAULT);

        NodeBuilder builder = NodeBuilder.nodeBuilder();
        Preconditions.checkArgument(config.containsKey(ES_YML_KEY) || config.containsKey(GraphDatabaseConfiguration.STORAGE_DIRECTORY_KEY),
                "Must either configure configuration file or base directory");
        if (config.containsKey(ES_YML_KEY)) {
            String configFile = config.getString(ES_YML_KEY);
            log.debug("Configuring ES from YML file [{}]", configFile);
            Settings settings = ImmutableSettings.settingsBuilder().loadFromSource(configFile).build();
            builder.settings(settings);
        } else {
            String dataDirectory = config.getString(GraphDatabaseConfiguration.STORAGE_DIRECTORY_KEY);
            log.debug("Configuring ES with data directory [{}]", dataDirectory);
            File f = new File(dataDirectory);
            if (!f.exists()) f.mkdirs();
            ImmutableSettings.Builder b = ImmutableSettings.settingsBuilder();
            for (String sub : DATA_SUBDIRS) {
                String subdir = dataDirectory + File.separator + sub;
                f = new File(subdir);
                if (!f.exists()) f.mkdirs();
                b.put("path." + sub, subdir);
            }
            builder.settings(b.build());

            String clustername = config.getString(CLUSTER_NAME_KEY, CLUSTER_NAME_DEFAULT);
            Preconditions.checkArgument(StringUtils.isNotBlank(clustername), "Invalid cluster name: %s", clustername);
            builder.clusterName(clustername);
        }

        node = builder.client(clientOnly).data(!clientOnly).local(local).node();
        client = node.client();

    } else {
        ImmutableSettings.Builder settings = ImmutableSettings.settingsBuilder();
        if (config.containsKey(CLUSTER_NAME_KEY)) {
            String clustername = config.getString(CLUSTER_NAME_KEY, CLUSTER_NAME_DEFAULT);
            Preconditions.checkArgument(StringUtils.isNotBlank(clustername), "Invalid cluster name: %s", clustername);
            settings.put("cluster.name", clustername);
        } else {
            settings.put("client.transport.ignore_cluster_name", true);
        }
        log.debug("Transport sniffing enabled: {}", config.getBoolean(CLIENT_SNIFF_KEY, CLIENT_SNIFF_DEFAULT));
        settings.put("client.transport.sniff", config.getBoolean(CLIENT_SNIFF_KEY, CLIENT_SNIFF_DEFAULT));
        TransportClient tc = new TransportClient(settings.build());
        for (String host : config.getStringArray(GraphDatabaseConfiguration.HOSTNAME_KEY)) {
            String[] hostparts = host.split(":");
            String hostname = hostparts[0];
            int hostport = HOST_PORT_DEFAULT;
            if (hostparts.length == 2) hostport = Integer.parseInt(hostparts[1]);
            log.info("Configured remote host: {} : {}", hostname, hostport);
            tc.addTransportAddress(new InetSocketTransportAddress(hostname, hostport));
        }
        client = tc;
        node = null;
    }

    maxResultsSize = config.getInt(MAX_RESULT_SET_SIZE_KEY, MAX_RESULT_SET_SIZE_DEFAULT);
    log.debug("Configured ES query result set max size to {}", maxResultsSize);

    client.admin().cluster().prepareHealth()
            .setWaitForYellowStatus().execute().actionGet();

    //Create index if it does not already exist
    IndicesExistsResponse response = client.admin().indices().exists(new IndicesExistsRequest(indexName)).actionGet();
    if (!response.isExists()) {
        CreateIndexResponse create = client.admin().indices().prepareCreate(indexName).execute().actionGet();
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            throw new TitanException("Interrupted while waiting for index to settle in", e);
        }
        if (!create.isAcknowledged()) throw new IllegalArgumentException("Could not create index: " + indexName);
    }
}

转载于:https://my.oschina.net/lvzunwei/blog/687813

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值