Elasticsearch學習總結二 elasticSearch一些基本用法

一 . elasticSearch提供了一些基本的rest命令,基本以下:python

  • /index/_search    搜索指定索引下的數據,http://ip:9200/index/_search 查詢當前索引下的數據
  • /index/                 查看指定索引的詳細信息
  • /index/type/          建立或操做類型
  • /index/_mapping    建立或操做mapping
  • /index/_settings      建立或操做設置(number_of_shards是不可更改的)
    
    使用rest命令的時候通常都是配合着curl命令一塊兒使用,例如
  • curl -x 指定http請求的方法 HEAD GET POST PUT DELETEgit

  • -d   指定要傳輸的數據
  • 建立索引的時候可使用以下命令github

  • curl -XPUT 'http://localhost:9200/index_name/'
  • 固然使用PUT/POST均可以,建立索引帶有數據使用以下命令
curl -XPOST http://localhost:9200/test/employee/1 -d '{
"first_name" : "John",
"last_name" : "Smith",
"age" : 25,
"about" : "I love to go rock climbing",
"interests": [ "sports", "music" ]
}'

二. 雖然可使用rest命令能夠靈活操做es,可是真正平時開發確定是用Java或者python了,下面看下JavaApi如何操做es.app

首先構建客戶端curl

Client client = TransportClient.builder().build()
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));

由於這些操做基本能夠封裝爲一個工具類,因此對建立客戶端作了一層封裝。工具

EsSearchManager esSearchManager = EsSearchManager.getInstance();
   esSearchManager.buildIndex("testIndex","testType");

在EsSearchManger構建實例的時候建立了ecClient,經過單例模式保證對象的惟一。ui

private EsSearchManager(){
		getClient();
}
public static EsSearchManager getInstance(){
		if(null == esSearchManager ){
			synchronized (EsSearchManager.class){
				esSearchManager = new EsSearchManager();
			}
		}
		return  esSearchManager;
	}

getClient()封裝了建立client的細節不在贅述,下面是構建索引的代碼,部分配置封裝到了配置文件中,放置硬編碼形成的修改麻煩,下面這個方法只是構建了索引,固然能夠指定mapping設置,只是封裝到了另外一個方法中。編碼

public Boolean buildIndex(String indexName) throws Exception {
		IndicesExistsResponse response = getClient().admin().indices()
				.prepareExists(indexName).execute().actionGet();
		Boolean flag = true;
		ResourceBundle rb = ResourceBundle.getBundle("commons");
		String replicas = rb.getString("replicas");
		String shards = rb.getString("shards");
		String refreshInterval = rb.getString("refreshInterval");
		if (!response.isExists()) { //須要將配置放置到配置文件中
			Settings settings = Settings.settingsBuilder()
					.put("number_of_replicas", Integer.parseInt(replicas))
					.put("number_of_shards", Integer.parseInt(shards))
					.put("index.translog.flush_threshold_ops", 10000000)
					.put("refresh_interval", refreshInterval)
					.put("index.codec", "best_compression").build();
			CreateIndexResponse createIndxeResponse = getClient().admin().indices()
					.prepareCreate(indexName).setSettings(settings).execute()
					.actionGet();
			flag = createIndxeResponse.isAcknowledged();
			LOG.info("返回值" + flag);
		}
		return flag;
	}

至此索引建立完畢,經過head插件能夠迅速查看到,詳細的代碼已將上傳至github中,地址以下 https://github.com/winstonelei/BigDataToolsurl

相關文章
相關標籤/搜索