可能的原因:
1、項目引用的ES版本和ES服務的版本不一樣;
2、端口不正確,tcp訪問端口是9300;
3、cluster.name不正確,可以通過訪問http://localhost:9200/查看ES服務下的cluster.name;
4、ES服務沒啟動;
簡單demo:
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
public class ElasticDemo {
//測試demo
@SuppressWarnings({ "resource", "unchecked" })
public static void main(String[] aa) throws UnknownHostException {
TransportClient client = null;
Settings esSettings = Settings.builder()
.put("cluster.name", "elasticsearch") //設置ES實例的名稱
.build();
client = new PreBuiltTransportClient(esSettings)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
System.out.println("ElasticsearchClient 連接成功");
// BulkRequestBuilder bulkRequest = client.prepareBulk();
// try {
// bulkRequest.add(client.prepareIndex("ko", "test", "14")
// .setSource(jsonBuilder()
// .startObject()
// .field("tableId", "14")
// .field("title", "tetstcccfffffccccccccccc")
// .field("content", "ttttttttfffffffttttttttttt")
// .endObject()
// )
// );
// } catch (IOException e) {
// e.printStackTrace();
// }
// BulkResponse bulkResponse = bulkRequest.get();
// if (bulkResponse.hasFailures()) {
// System.out.println("失敗:" + bulkResponse.toString());
// }
// System.out.println("操作成功");
HighlightBuilder highlightBuilder = new HighlightBuilder().field("title").requireFieldMatch(true);
highlightBuilder.preTags("<span style=\"color:red\">");
highlightBuilder.postTags("</span>");
highlightBuilder.boundaryMaxScan(4);
SearchRequestBuilder searchRequestBuilder = client.prepareSearch("ko"); //可以是多個index
//searchRequestBuilder.setQuery(QueryBuilders.termQuery("title", "ffff")); //精確查詢
searchRequestBuilder.setQuery(QueryBuilders.wildcardQuery("title", "*文 el*")); //模糊查詢
searchRequestBuilder.setFrom(0);
searchRequestBuilder.setSize(2);
searchRequestBuilder.highlighter(highlightBuilder);
SearchResponse response = searchRequestBuilder.get();
System.out.println(response);
}
}
