rubber-band-being-flicked

弹性 – 6.4.3

使用弹性工作很有趣。只需使用查询字符串 URL 或使用 Java 高级/低级客户端编写 Java 程序即可使用并返回结果。

在本博客中,我将编写一个简单的 Java 服务,它将在弹性搜索查询之上公开特定计算。您可以在elastic.io阅读更多内容

我将编写一个简单的 Sprint Boot 应用程序,该应用程序将公开几个终结点,允许用户在预定义的索引上调用查询,这些索引可以自定义。

您可能还喜欢:搜索 ELK(堆栈):数据监控到可视化

第 1 步:依赖项检查

我使用的版本和库是:

  • 依赖项 Java-JDK 1.8 (采用OpenJDK)。
  • 马文 3.
  • 弹簧启动= 2.2.1。释放。

有人可能会问,为什么要在服务之上编写服务。嗯,在我的例子中,我想运行一个特定的查询,必须公开为URL而不是请求正文,不幸的是,我不得不处理的版本是6.4.3,而不是最新的7.4,这本来可以使这个过程简单得多。

目的

将两个终结点公开为 REST 终结点(不安全):

  • /es 返回有关群集和 ES 版本的自定义信息。

  • /metric 返回自定义查询的响应(更多信息如下)。

第 2 步:Spring.io启动器

与大多数示例博客一样,我从https://start.spring.io/开始创建项目空间。

聚 甲醛。Xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

<packaging>war</packaging>
<groupId>net.my.ops</groupId>
<artifactId>metrics</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>metrics</name>
<description>Metrics counter</description>

<properties>
<java.version>1.8</java.version>
<spring.boot.version>2.0.0.RELEASE</spring.boot.version>
<maven.compiler.sources>1.8</maven.compiler.sources>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>

<dependencies>


<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>${spring.boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>${spring.boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>

<dependency>
<groupId>org

引导</组Id>
<工件Id>弹簧启动-启动-测试</工件Id>
<范围>测试</范围>
<排除>
<排除>
<groupId>org.junit.vintage</组Id>
<工件Id>君子-发动机</工件Id>
</排除>
</排除>
</依赖项>
</依赖项>

<build>
<最终名称>$[工件Id]</最终名称>
<插件>
<插件>
<groupId>org.springframework.boot</组Id>
<工件Id>弹簧启动-母插件</工件Id>
<版本>${spring.boot.version_lt;/版本>
</插件>
</插件>
</build>

</项目>

我们需要在 RestHighLevelClient POM.xml文件中添加依赖项。

       <dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>${elastic.version}</version>
</dependency>

<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>${elastic.version}</version>
</dependency>
<properties>
   <elastic.version>6.4.3</elastic.version>
</properties>

定义 pom 后,是时候开始编写代码了。我确实增加了一些调试详细信息,以检查启动应用程序时将创建的所有 bean。有关命令线运行者的更多信息,请参阅此处。

@SpringBootApplication
public class MetricsApplication {

public static void main(String[] args) {
SpringApplication.run(MetricsApplication.class, args);
}

@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return args -> {

System.out.println("Let's inspect the beans provided by Spring Boot:");

String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
System.out.println(beanName);
}

};
}

}

我做的第一件事是为项目添加一个应用程序.properties,其中包含主机名和所需的索引信息

elasticsearch.host=myhostname.samarthya.me
metrics.index=my_alarm_index_1_1

第 3 步:新对象

定义属性后,是时候创建将构造 ES 的高级客户端的配置对象了。

@Configuration
public class ElasticsearchConfig {

    @Value("${elasticsearch.host}")
    private String elasticsearchHost;

    @Value("${metrics.index}")
    private String indexName;

    @Bean(destroyMethod = "close")
    public RestHighLevelClient client() {

        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost(elasticsearchHost)));

        return client;

    }

    @Bean()
    public SearchRequest searchRequest()
    {
        SearchRequest searchRequest = new SearchRequest(indexName);
        return searchRequest;
    }

}

它是创建 RestHighLevelClientSearchRequest 的简单定义。更多详情可在elastic.io网站查阅。

基本构建基块可用,因此,现在,是时候定义一个服务,在调用 ES 时调用搜索。

@Service
public class MetricService {
    private RestHighLevelClient restClient;
    private SearchRequest searchRequest;

    @Autowired
    public MetricService(RestHighLevelClient restClient, SearchRequest searchRequest) {
        this

搜索请求 = 搜索请求;
}

/= 从响应中读取的群集信息 */
公共字符串群集Info() |
尝试*
主要响应 = restClient.info(请求选项.DEFAULT);

X内容生成器生成器 = XContentFactory.jsonBuilder(.startObject()
.field(”名称”,响应.getclusterName(.toString())
.field(”版本”,响应.getVersion(.toString())
.endObject();
返回字符串.到String(生成器);
[渔获量(IO 异常(前)]
系统.out.println(例如getMessage));
}

返回”错误:500″;

}

/= 具有”必须”和”应”的复合查询的指标信息 */
公共字符串 getMetric() |

搜索来源构建器搜索来源构建器 = 新的搜索源构建器();
搜索来源Builder.超时(新时间价值(60,时间单位.秒针);新时间值(60,时间单位.秒针);
搜索来源Builder.size(1);
搜索来源Builder.sort(新字段排序生成器(”@timestamp”订单(排序订单.DESC);”
布尔查询构建器布尔查询构建器 = 查询构建器.boolQuery();

列表<查询构建器>必须查询 = 新链接列表\lt;查询生成器>();

必须查询.add(查询构建器.术语查询(”header_item_for”,”用户”);
必须查询.add(查询构建器.术语查询(”metric_name”、”成功登录”);

boolQueryBuilder.must(.add.add(查询构建器.范围查询(”时间戳”gt(”现在-5米/米”)(”现在/米”);
boolQueryBuilder.应(.addAll(必须查询);

搜索来源Builder.查询(boolQueryBuilder);
系统.out.println(boolQueryBuilder.toString());
此.searchRequest.source(搜索源构建器);

搜索响应搜索响应 = null;
字符串输出 = null;
尝试 |
搜索响应 = restClient.search(此.search 请求,请求选项.DEFAULT);

如果 (搜索响应 != 空) |
System.out.println(”找到结果”);
输出 = 搜索响应.toString();
}
[ 渔获量 (弹性搜索状态异常 ex) ]
系统.out.println(例如getMessage));
}
渔获物(IO异常(前) |
System.out.println(”ex:”= ex.getMessage());
}
返回输出;
}

}

此处定义的两种方法旨在由我将公开的两个其余终结点使用。

群集信息()

它将 ES 版本信息作为 JSON 返回,其中具有两个信息字段,名称和版本。

getMetric()

它返回一个文档,该文档的正和 是 文档中 header_item_for users metric_name SuccessfulLogin 的字段。另一个限制条件是文档应在过去 7 分钟(从现在开始)的时间窗口内生成。

第 4 步:控制器


@RestController
public class MetricController {


    private MetricService metricService;

    @Autowired
    public MetricController(MetricService metricService) {
        this.metricService = metricService;
    }

    @RequestMapping("/")
    public ServiceVersion defaultHandler() {
        return getVersionInformation();
    }

    @RequestMapping("/metric")
    public String ElasticQuery() {
        return metricService.getMetric();
    }

    @RequestMapping("/es")
    public String getVersionInformation() {
        return metricService.clusterInfo();
    }
}

控制器将终结点与公开的服务终结点连接。如果我运行了应用程序(并且索引存在),我可以看到搜索查询的结果。

总之,我刚刚演练了一个示例程序,通过该程序,您可以执行查询(使用查询生成器和搜索请求)和Java 高级客户端 (v6com/refcardz/开始与阿帕奇-托姆卡特”rel=”不跟随”-吨级。

进一步阅读

Comments are closed.