java REST 和复杂的搜索查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13110147/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
REST and complex search queries
提问by GlennV
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;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
/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.The search format does not have to be the same as I listed above.
- Allows me to map that Criteria model to any technologyI need to use.
- Offers mapping support for Hibernate/JPA/SQL, but this is a bonus ;)
- 将指定为字符串的搜索查询映射到通用 Criteria 模型。搜索格式不必与我上面列出的相同。
- 允许我将该 Criteria 模型映射到我需要使用的任何技术。
- 为 Hibernate/JPA/SQL 提供映射支持,但这是一个奖励;)
Kind regards,
亲切的问候,
Glenn
格伦
采纳答案by Tom Howard
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 constraintspecifies that we must include the hypermedia controls (links and forms) in our responses. 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):
HATEOAS 约束指定我们必须在响应中包含超媒体控件(链接和表单)。所以假设我们有一个/cars
带有搜索选项的分页汽车集合,这样当你得到/cars
它时会返回类似的东西(顺便说一句,我在这里使用自定义媒体类型,但表格和链接应该很明显。让我知道如果不是):
<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:
所以只要说我们搜索白色汽车,我们会得到/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
这个结果然后让我们细化我们的查询。所以只要说我们想要白色汽车而不是“白色”汽车,我们就可以得到 '/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. e.g., 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 (i.e., 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.
有没有图书馆可以为您做到这一点?我所知道的都没有。我见过的大多数甚至都不支持超媒体控件(即,您必须自己添加链接和表单)。有你可以使用的模式吗?是的,我相信以上是解决此类问题的有效模式。
回答by Deepak Bala
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. It gets weird after a point.
嗯……这是一个棘手的领域。没有适合您的问题的框架。甚至@p0wl 提到的 ODATA 对字段映射到域模型的方式也有一定的限制。过了一会就很奇怪了。
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. 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.
解决此问题的最简单方法是将查询作为字符串接受,然后您可以使用 AST 或任何您想要的特定领域语言对其进行验证。这使您可以灵活地接受查询,同时仍然验证它的正确性。你失去的是通过 URL 以更有意义的方式描述查询的能力。
Take a look at chapter 8of the Restful recipes cookbook. 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.
看看Restful 食谱食谱的第 8 章。它突出了我提出的解决方案之一,并推荐了其他方法。根据客户所需的灵活性与查询的表达能力选择一种。您可以在某处取得平衡。
回答by ioseb
@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)
- Client's may construct URIs by rules defined by media type or other spec.
- 客户端可以通过“Link: <...>”标头或实体主体(如原子或 HTML 链接或类似内容)跟踪包含在 HTTP 标头中的链接
- 客户端可以通过媒体类型或其他规范定义的规则构造 URI。
Several well known approaches of guided URI construction process:
引导式 URI 构建过程的几种众所周知的方法:
- HTML GET forms where form fields are encoded according to RFC3986and appended to the URI provided in form's action attribute value(media type guided);
- URI Templates(quite broad though worths reading, spec offers really interesting features) RFC6570
- Open search queries(media type guided)
- HTML GET 表单,其中表单字段根据RFC3986进行编码并附加到表单的操作属性值中提供的 URI(媒体类型引导);
- URI 模板(相当广泛但值得一读,规范提供了非常有趣的功能)RFC6570
- 打开搜索查询(媒体类型引导)
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(i.e. 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.
- 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).
- 连接器- 包括 HTTP + URI 规范,实际上只有连接器对客户端很重要。
- 组件- 这是底层实现,除了你没有人关心。这部分需要对客户端完全隐藏,您可以在这里选择任何绑定方式,没有人可以告诉您确切的方式,这完全取决于特定的要求。
回答by p0wl
回答by juancancela
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/). Using the CrudRepository you can get methods like findOne, findAll, etc. AND, if you extend it, you can add your own generic mappings. 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. Or, for example: customer?country=like(Island) to get all customers with country like "Island" (in a SQL way). Hope it helps.
如前所述,仍然没有通用的解决方案来做到这一点。可能,最好的选择(至少是我找到的最好的)是 Spring DATA REST(http://static.springsource.org/spring-data/rest/docs/1.1.0.M1/reference/htmlsingle/)。使用 CrudRepository,您可以获得 findOne、findAll 等方法。并且,如果您扩展它,您可以添加您自己的通用映射。例如,我们所做的是将其扩展为具有通用查询选项,例如:customer?country=notArgentina,以获取不属于阿根廷的客户。或者,例如: customer?country=like( Island) 获取所有国家为“Island”之类的客户(以 SQL 方式)。希望能帮助到你。