文档章节

elasticsearch 实例大全

Evyn_lv
 Evyn_lv
发布于 2016/06/06 17:58
字数 2103
阅读 25
收藏 0

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 code Vote up 9 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 code Vote up 6 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 code Vote up 6 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 code Vote up 6 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 code Vote up 6 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 code Vote up 6 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 code Vote up 6 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 code Vote up 6 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 code Vote up 6 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 code Vote up 6 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 code Vote up 6 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 code Vote up 6 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 code Vote up 6 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 code Vote up 6 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 code Vote up 6 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 code Vote up 6 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 code Vote up 6 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 code Vote up 6 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 code Vote up 5 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 code Vote up 5 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);
    }
}

© 著作权归作者所有

Evyn_lv
粉丝 2
博文 76
码字总数 49292
作品 0
杭州
高级程序员
私信 提问
elasticsearch windows 安装

elasticsearch 安装 1、elasticsearch下载 下载链接:https://www.elastic.co/downloads/past-releases jdk依赖:elasticsearch 2.x依赖的jdk版本是1.7,elasticsearch 5.x依赖的jdk版本是1......

晴天哥
2017/06/11
0
0
centos 7( linux )下安装elasticsearch教程

目录 概述 环境准备 elaticsearch简介 安装elasticsearch 彩蛋 概述 很久没有写博客了,最近在做全文检索的项目,发现elasticsearch踩了不少坑,百度点进去又是坑,在此记录一下自己的踩坑历程。...

java_龙
2018/10/15
538
0
如何在 MacOS 上安装 Kibana

Elasticsearch 安装好了之后,Kibana 插件可以为这个功能强大的搜索工具添加可视化功能。 在我之前的文章中,我向 Mac 用户介绍了安装 Elasticsearch 的步骤,这是世界上最受欢迎的企业级搜索...

作者: Lauren Maffeo
07/22
0
0
ElasticSearch入门 —— 集群搭建

一、环境介绍与安装准备 1、环境说明 2台虚拟机,OS为ubuntu13.04,ip分别为xxx.xxx.xxx.140和xxx.xxx.xxx.145。 2、安装准备 ElasticSearch(简称ES)由java语言实现,运行环境依赖java。E...

萧十一郎君
2014/04/30
57.2K
3
深度课程:Elasticsearch从原理到实战(广州)

本次课程将于2017年11月25日在广州举办,深度课程:Elasticsearch从原理到实战(广州)报名平台活动家。 在线报名通道:https://www.huodongjia.com/event-1468573944.html 在大数据领域,E...

活动家
2017/09/29
26
0

没有更多内容

加载失败,请刷新页面

加载更多

nginx学习之模块

1、 stub_status模块: 用于展示nginx处理连接时的状态。 配置语法如下: Syntax:stub_status;Default:默认没有配置Context:server、location 可以编辑default.conf,加上如下配置: ...

码农实战
52分钟前
4
0
MySQL,必须掌握的6个知识点

目录 一、索引B+ Tree 原理 MySQL 索引 索引优化 索引的优点 索引的使用条件 二、查询性能优化使用 Explain 进行分析 优化数据访问 重构查询方式 三、存储引擎InnoDB MyISAM 比较 四、数据类...

李红欧巴
56分钟前
4
0
堆”和“栈

C++作为一款C语言的升级版本,具有非常强大的功能。它不但能够支持各种程序设计风格,而且还具有C语言的所有功能。我们在这里为大家介绍的是其中一个比较重要的内容,C++内存区域的基本介绍。...

SibylY
今天
4
0
总结:Https

一、介绍 简单理解,https即在http协议的基础上,增加了SSL协议,保障数据传输的安全性。 它由以前的http—–>tcp,改为http——>SSL—–>tcp;https采用了共享密钥加密+公开密钥加密的方式 ...

浮躁的码农
今天
6
0
数据库表与表之间的一对一、一对多、多对多关系

表1 foreign key 表2 多对一:表 1 的多条记录对应表 2 的一条记录 利用foreign key的原理我们可以制作两张表的多对多,一对一关系 多对多: 表1的多条记录可以对应表2的一条记录 表2的多条记...

Garphy
今天
7
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部