简体   繁体   English

REST和复杂的搜索查询

[英]REST and complex search queries

I'm looking for a robust way to model search queries in a REST api. 我正在寻找一种在REST API中建模搜索查询的强大方法。

In my api, you can specify the search criteria in the URI of a resource using query parameters. 在我的api中,您可以使用查询参数在资源的URI中指定搜索条件。

For example: 例如:

/cars?search=color,blue;AND;doors,4 --> Returns a list of blue cars with 4 doors

/cars?search=color,blue;OR;doors,4 --> Returns a list of cars that are blue or have 4 doors

On the server side, the search string is mapped to the desired underlying technology. 在服务器端,搜索字符串映射到所需的基础技术。 Depending on the rest resource, this can be a SQL query, the Hibernate Criteria api, another webservice call, ... 根据其余资源,这可以是SQL查询,Hibernate Criteria api,另一个Web服务调用,......

The 2 examples are simple enough to support, but I also need more complex search features like substring search, searching before/after dates, NOT, ... 这两个例子很简单,但我还需要更复杂的搜索功能,如子字符串搜索,日期之前/之后搜索,NOT,...

This is a common problem I think. 这是我认为的常见问题。 Is there a library (or a pattern) that I can use that: 是否有我可以使用的库(或模式):

  • Maps search queries specified as a string to a generic Criteria model. 将指定为字符串的搜索查询映射到通用Criteria模型。 The search format does not have to be the same as I listed above. 搜索格式不必与上面列出的相同。
  • Allows me to map that Criteria model to any technology I need to use. 允许我将Criteria模型映射到我需要使用的任何技术
  • Offers mapping support for Hibernate/JPA/SQL, but this is a bonus ;) 为Hibernate / JPA / SQL提供映射支持,但这是一个奖励;)

Kind regards, 亲切的问候,

Glenn 格伦

Whenever I face these problems, I ask myself "How would I present this to a user, if I was creating a traditional webpage"? 每当我遇到这些问题时,我会问自己“如果我正在创建传统网页,我将如何向用户展示”? The simple answer is that I wouldn't present those sort of options in a single page. 简单的答案是我不会在一个页面中提供这些选项。 The interface would be too complex; 界面太复杂了; however what I could do is provide an interface that allowed users to build up more and more complex queries over a number of pages and that's the solution I think you should go for in this case. 但我能做的是提供一个界面,允许用户在多个页面上构建越来越复杂的查询,这是我认为你应该在这种情况下应该采用的解决方案。

The HATEOAS constraint specifies that we must include the hypermedia controls (links and forms) in our responses. HATEOAS约束指定我们必须在响应中包含超媒体控件(链接和表单)。 So let's say we have a paginated collections of cars at /cars with a search option, so that when you get /cars it returns something like (BTW I'm using a custom media-type here, but the forms and links should be pretty obvious. Let me know if it isn't): 所以,假设我们在/cars有一个带有搜索选项的汽车的分页集合,所以当你得到/cars它返回的东西(BTW我在这里使用自定义媒体类型,但表格和链接应该很漂亮显而易见。如果不是,请告诉我):

<cars href="/cars">
    <car href="/cars/alpha">...</car>
    <car href="/cars/beta">...</car>
    <car href="/cars/gamma">...</car>
    <car href="/cars/delta">...</car>
    ...
    <next href="/cars?page=2"/>
    <search-color href="/cars" method="GET">
        <color type="string" cardinality="required"/>
        <color-match type="enumeration" cardinality="optional" default="substring">
            <option name="exact"/>
            <option name="substring"/>
            <option name="regexp"/>
        </color-match>
        <color-logic type="enumeration" cardinality="optional" default="and">
            <option name="and"/>
            <option name="or"/>
            <option name="not"/>
        </color-logic>
    </search>
    <search-doors href="/cars" method="GET">
        <doors type="integer" cardinality="required"/>
        <door-logic type="enumeration" cardinality="required" default="and">
            <option name="and"/>
            <option name="or"/>
            <option name="not"/>
        </door-logic>
    </search>
</cars>

So just say we search for white cars, we would GET /cars?color=white and we might get back something like: 所以只要说我们搜索白色汽车,我们会GET /cars?color=white ,我们可能会得到类似的东西:

<cars href="/cars?color=white">
    <car href="/cars/beta">...</car>
    <car href="/cars/delta">...</car>
    ...
    <next href="/cars?color=white&page=2"/>
    <search-color href="/cars?color=white" method="GET">
        <color2 type="string" cardinality="required"/>
        <color2-match type="enumeration" cardinality="optional" default="substring">
            <option name="exact"/>
            <option name="substring"/>
            <option name="regexp"/>
        </color2-match>
        <color2-logic type="enumeration" cardinality="optional" default="and">
            <option name="and"/>
            <option name="or"/>
            <option name="not"/>
        </color2-logic>
    </search>
    <search-doors href="/cars?color=white" method="GET">
        <doors type="integer" cardinality="required"/>
        <door-logic type="enumeration" cardinality="required" default="and">
            <option name="and"/>
            <option name="or"/>
            <option name="not"/>
        </door-logic>
    </search>
</cars>

This result then let's us refine our query. 然后,这个结果让我们改进我们的查询。 So just say we wanted white cars but not "off-white" cars, we could then GET '/cars?color=white&color2=off-white&color2-logic=not', which might return 所以只是说我们想要白色车而不是“灰白色”车,我们可以GET'/ cars?color = white&color2 = off-white&color2-logic = not',这可能会返回

<cars href="/cars?color=white&color2=off-white&color2-logic=not">
    <car href="/cars/beta">...</car>
    <car href="/cars/delta">...</car>
    ...
    <next href="/cars?color=white&color2=off-white&color2-logic=not&page=2"/>
    <search-color href="/cars?color=white&color2=off-white&color2-logic=not" method="GET">
        <color3 type="string" cardinality="required"/>
        <color3-match type="enumeration" cardinality="optional" default="substring">
            <option name="exact"/>
            <option name="substring"/>
            <option name="regexp"/>
        </color3-match>
        <color3-logic type="enumeration" cardinality="optional" default="and">
            <option name="and"/>
            <option name="or"/>
            <option name="not"/>
        </color3-logic>
    </search>
    <search-doors href="/cars?color=white&color2=off-white&color2-logic=not" method="GET">
        <doors type="integer" cardinality="required"/>
        <door-logic type="enumeration" cardinality="required" default="and">
            <option name="and"/>
            <option name="or"/>
            <option name="not"/>
        </door-logic>
    </search>
</cars>

We could then further refine our query, but the point is that at each step along the way, the hypermedia controls tells us what is possible. 然后我们可以进一步优化我们的查询,但重点是在整个过程中的每一步,超媒体控件告诉我们什么是可能的。

Now, if we think about the search options for cars, the colors, doors, makes and models aren't unbounded, so we could make the options more explicit by providing enumerations. 现在,如果我们考虑汽车的搜索选项,颜色,门,品牌和模型都不是无限制的,所以我们可以通过提供枚举来使选项更加明确。 For instance 例如

<cars href="/cars">
    ...
    <search-doors href="/cars" method="GET">
        <doors type="enumeration" cardinality="required">
            <option name="2"/>
            <option name="3"/>
            <option name="4"/>
            <option name="5"/>
        </doors>
        <door-logic type="enumeration" cardinality="required" default="and">
            <option name="and"/>
            <option name="or"/>
            <option name="not"/>
        </door-logic>
    </search>
</cars>

However the only white cars that we have might be 2 and 4 door, in which case GETing /cars?color=white might give us 然而,我们唯一的白色车可能是2门和4门,在这种情况下GETing /cars?color=white可能会给我们带来帮助

<cars href="/cars?color=white">
    ...
    <search-doors href="/cars?color=white" method="GET">
        <doors type="enumeration" cardinality="required">
            <option name="2"/>
            <option name="4"/>
        </doors>
        <door-logic type="enumeration" cardinality="required" default="and">
            <option name="and"/>
            <option name="or"/>
            <option name="not"/>
        </door-logic>
    </search>
</cars>

Similarly, as we refine the colors, we might find their are only a few options, in which case we can switch from providing a string search, to providing an enumeration search. 类似地,当我们改进颜色时,我们可能会发现它们只有几个选项,在这种情况下我们可以从提供字符串搜索切换到提供枚举搜索。 eg, GETing /cars?color=white might give us 例如,GETing /cars?color=white可能会给我们

<cars href="/cars?color=white">
    ...
    <search-color href="/cars?color=white" method="GET">
        <color2 type="enumeration" cardinality="required">
            <option name="white"/>
            <option name="off-white"/>
            <option name="blue with white racing stripes"/>
        </color2>
        <color2-logic type="enumeration" cardinality="optional" default="and">
            <option name="and"/>
            <option name="or"/>
            <option name="not"/>
        </color2-logic>
    </search>
    ...
</cars>

You could do the same for other search categories. 您可以对其他搜索类别执行相同操作。 For instance, initially you wouldn't want to enumerate all the makes, so you would provide some sort of text search. 例如,最初你不想枚举所有的品牌,所以你会提供某种文字搜索。 Once the collection has been refined, and there are only a few models to pick from, then it makes sense to provide an enumeration. 一旦集合被细化,并且只有几个模型可供选择,那么提供枚举是有意义的。 The same logic applies to other collections. 同样的逻辑适用于其他集合。 For instance you wouldn't want to enumerate all of the cities in the world, but once you have refined the area to 10 or so cities, then enumerating them can be very helpful. 例如,你不想列举世界上所有的城市,但是一旦你将这个区域精炼到10个左右的城市,那么枚举它们会非常有帮助。

Is there a library that will do this for you? 有没有一个图书馆会为你做这个? None that I know of. 我不知道。 Most I've seen don't even support hypermedia controls (ie, you've got to add the links and forms yourself ). 我见过的大多数人甚至不支持超媒体控件(即你必须自己添加链接和表单 )。 Is there a pattern you can use? 你有可以使用的模式吗? Yes, I believe the above is a valid pattern for solving this sort of problem. 是的,我相信以上是解决此类问题的有效模式。

hmmm... this is a tricky area. 嗯......这是一个棘手的领域。 There is no framework out there that is tailored for your problem. 没有针对您的问题量身定制的框架。 Even ODATA that @p0wl mentions has certain limitations about the way fields are mapped to domain models. 甚至@ p0wl提到的ODATA对字段映射到域模型的方式也有一定的限制。 It gets weird after a point. 一点之后变得奇怪。

The simplest way to get around this is to accept the query as a String which you then validate against a domain specific language using a AST or whatever it is that you want. 解决此问题的最简单方法是将查询作为String接受,然后使用AST或您想要的任何内容对域特定语言进行验证。 This allows you to be flexible while accepting the query while still validating it for correctness. 这使您可以在接受查询时保持灵活性,同时仍然可以验证查询的正确性。 What you lose is the ability to describe the query in a more meaningful manner through the URL. 您失去的是能够通过URL以更有意义的方式描述查询。

Take a look at chapter 8 of the Restful recipes cookbook. 看看Restful食谱食谱的第8章 It highlights one of the solutions I proposed and also recommends other approaches. 它强调了我提出的解决方案之一,并建议采用其他方法。 Choose one based on the flexibility needed by your client versus the expressiveness of your query. 根据客户所需的灵活性与查询的表现力选择一个。 There is a balance you can strike somewhere. 你可以在某个地方找到平衡点。

@GlennV @GlennV

I'm not sure there is a pattern/rule directly related to this and if this is a common problem(i mean logical operators in query string), but i'd ask following question to myself when designing something like this: 我不确定是否存在与此直接相关的模式/规则,如果这是一个常见问题(我的意思是查询字符串中的逻辑运算符),但在设计这样的事情时我会问自己以下问题:

  • How client is going to construct such queries? 客户如何构建此类查询?

The problem is that URIs(as a whole, including query string part) must be entirely controlled by service provider and clients must not be directly coupled to URI construction logic which are specific to your problem domain. 问题是URI(作为一个整体,包括查询字符串部分)必须完全由服务提供者控制,并且客户端不能直接耦合到特定于您的问题域的URI构造逻辑。

There are several ways how clients use URIs and how they construct them: 客户端使用URI以及构造它们的方式有多种:

  • Client's may follow links which are included either in HTTP headers via "Link: <...>" header or in entity body(like atom or HTML links or something similar) 客户端可以跟随链接,这些链接通过“链接:<...>”标题或实体主体(如原子或HTML链接或类似内容)包含在HTTP标头中
  • Client's may construct URIs by rules defined by media type or other spec. 客户端可以按媒体类型或其他规范定义的规则构造URI。

Several well known approaches of guided URI construction process: 引导URI构建过程的几种众所周知的方法:

  • HTML GET forms where form fields are encoded according to RFC3986 and appended to the URI provided in form's action attribute value(media type guided); HTML GET表单,表单字段根据RFC3986编码,并附加到表单的操作属性值(媒体类型引导)中提供的URI;
  • URI Templates(quite broad though worths reading, spec offers really interesting features) RFC6570 URI模板(相当广泛但值得一读,规范提供了非常有趣的功能) RFC6570
  • Open search queries(media type guided) 打开搜索查询(媒体类型引导)

Based on information above you can choose existing approach or design your own but with simple rule in mind that service must coordinate clients how they can construct queries(ie define your own spec, custom media type, or extend existing). 根据上述信息,您可以选择现有方法或设计自己的方法,但要记住简单的规则,服务必须协调客户如何构建查询(即定义您自己的规范,自定义媒体类型或扩展现有)。

Another thing is how you are going to map URIs to underlying implementation and there are two very important things in terms of REST: 另一件事是你如何将URI映射到底层实现,在REST方面有两个非常重要的事情:

  • Connector - which includes HTTP + URI specs and actually only connector matters for clients. 连接器 - 包括HTTP + URI规范,实际上只有连接器对客户端很重要。
  • Component - which is underlying implementation and no one cares except you. 组件 - 这是底层实现,除了您之外没有人关心。 This part needs to be entirely hidden from clients and you can choose any binding approach here, no one can tell you exact way, it entirely depends on particular requirement(s). 这部分需要完全隐藏在客户端之外,你可以在这里选择任何绑定方法,没有人能告诉你确切的方法,它完全取决于特定的要求。

Do you search for a library like ODATA ( Link )? 你搜索像ODATA( Link )这样的图书馆吗?

This would solve your query parsing problems and you could just forward the query to the database of your choice. 这将解决您的查询解析问题,您只需将查询转发到您选择的数据库。

As mentioned before, still there isnt a generic solution to do this. 如前所述,仍然没有通用的解决方案来做到这一点。 Probably, the best option (at tleast the best ive found) is Spring DATA REST ( http://static.springsource.org/spring-data/rest/docs/1.1.0.M1/reference/htmlsingle/ ). 可能最好的选择(至少发现最好的ive)是Spring DATA REST( http://static.springsource.org/spring-data/rest/docs/1.1.0.M1/reference/htmlsingle/ )。 Using the CrudRepository you can get methods like findOne, findAll, etc. AND, if you extend it, you can add your own generic mappings. 使用CrudRepository,您可以获得findOne,findAll等方法。如果扩展它,您可以添加自己的通用映射。 In example, what we have done is to extend it to have generic query options like: customer?country=notArgentina, in order to get customers that does not belong to Argentina. 例如,我们所做的是将其扩展为具有通用查询选项,例如:customer?country = notArgentina,以便获得不属于阿根廷的客户。 Or, for example: customer?country=like( Island ) to get all customers with country like "Island" (in a SQL way). 或者,例如:customer?country = like( Island )以获得像“Island”这样的国家/地区的所有客户(以SQL方式)。 Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM