UNPKG

ravendb

Version:
501 lines 21.7 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DocumentQuery = exports.NESTED_OBJECT_TYPES_PROJECTION_FIELD = void 0; const AbstractDocumentQuery_js_1 = require("./AbstractDocumentQuery.js"); const index_js_1 = require("../../Exceptions/index.js"); const Constants_js_1 = require("../../Constants.js"); const QueryData_js_1 = require("../Queries/QueryData.js"); const GroupByDocumentQuery_js_1 = require("./GroupByDocumentQuery.js"); const FieldsToFetchToken_js_1 = require("./Tokens/FieldsToFetchToken.js"); const SpatialCriteriaFactory_js_1 = require("../Queries/Spatial/SpatialCriteriaFactory.js"); const TypeUtil_js_1 = require("../../Utility/TypeUtil.js"); const FacetBuilder_js_1 = require("../Queries/Facets/FacetBuilder.js"); const AggregationDocumentQuery_js_1 = require("../Queries/Facets/AggregationDocumentQuery.js"); const MoreLikeThisBase_js_1 = require("../Queries/MoreLikeThis/MoreLikeThisBase.js"); const MoreLikeThisUsingDocument_js_1 = require("../Queries/MoreLikeThis/MoreLikeThisUsingDocument.js"); const MoreLikeThisBuilder_js_1 = require("../Queries/MoreLikeThis/MoreLikeThisBuilder.js"); const MoreLikeThisUsingDocumentForDocumentQuery_js_1 = require("../Queries/MoreLikeThis/MoreLikeThisUsingDocumentForDocumentQuery.js"); const SuggestionBase_js_1 = require("../Queries/Suggestions/SuggestionBase.js"); const SuggestionDocumentQuery_js_1 = require("../Queries/Suggestions/SuggestionDocumentQuery.js"); const SuggestionBuilder_js_1 = require("../Queries/Suggestions/SuggestionBuilder.js"); const QueryIncludeBuilder_js_1 = require("./Loaders/QueryIncludeBuilder.js"); const FilterFactory_js_1 = require("../Queries/FilterFactory.js"); exports.NESTED_OBJECT_TYPES_PROJECTION_FIELD = "__PROJECTED_NESTED_OBJECT_TYPES__"; class DocumentQuery extends AbstractDocumentQuery_js_1.AbstractDocumentQuery { constructor(documentType, session, indexName, collectionName, isGroupBy, declareTokens, loadTokens, fromAlias, isProjectInto) { super(documentType, session, indexName, collectionName, isGroupBy, declareTokens, loadTokens, fromAlias, isProjectInto); } selectFields(propertiesOrQueryData, projectionType, projectionBehavior) { projectionBehavior ??= "Default"; if (this.isProjectInto || (this.fieldsToFetchToken?.projections?.length > 0)) { QueryData_js_1.QueryData.throwProjectionIsAlreadyDone(); } if (projectionType) { this._theSession.conventions.tryRegisterJsType(projectionType); } if (TypeUtil_js_1.TypeUtil.isString(propertiesOrQueryData)) { propertiesOrQueryData = [propertiesOrQueryData]; } if (Array.isArray(propertiesOrQueryData)) { if (projectionType) { return this._selectFieldsByProjectionType(propertiesOrQueryData, projectionType, projectionBehavior); } const queryData = new QueryData_js_1.QueryData(propertiesOrQueryData, propertiesOrQueryData); queryData.isProjectInto = true; queryData.projectionBehavior = projectionBehavior; return this.selectFields(queryData, projectionType); } else { propertiesOrQueryData.isProjectInto = true; const queryData = propertiesOrQueryData; // add nested object types to result, so we can properly read types if (!queryData.isCustomFunction) { queryData.fields = [...queryData.fields, `${Constants_js_1.CONSTANTS.Documents.Metadata.KEY}.${Constants_js_1.CONSTANTS.Documents.Metadata.NESTED_OBJECT_TYPES}`]; queryData.projections = [...queryData.projections, Constants_js_1.CONSTANTS.Documents.Metadata.NESTED_OBJECT_TYPES_PROJECTION_FIELD]; } // we don't assign here projection behavior as it comes from override which already holds proper behavior from QueryData // queryData.projectionBehavior = projectionBehavior; return this.createDocumentQueryInternal(projectionType, queryData); } } _selectFieldsByProjectionType(properties, projectionType, projectionBehavior) { if (!properties || !properties.length) { (0, index_js_1.throwError)("InvalidArgumentException", "Fields cannot be null or empty."); } try { const projections = properties; const fields = properties.map(x => x); const queryData = new QueryData_js_1.QueryData(fields, projections); queryData.projectionBehavior = projectionBehavior; return this.selectFields(queryData, projectionType); } catch (err) { (0, index_js_1.throwError)("RavenException", "Unable to project to type: " + projectionType, err); } } selectTimeSeries(timeSeriesQuery, projectionClass) { const queryData = this._createTimeSeriesQueryData(timeSeriesQuery); return this.selectFields(queryData, projectionClass); } distinct() { this._distinct(); return this; } orderByScore() { this._orderByScore(); return this; } orderByScoreDescending() { this._orderByScoreDescending(); return this; } includeExplanations(optionsOrExplanationsCallback, explanationsCallback) { if (arguments.length === 1) { return this.includeExplanations(null, optionsOrExplanationsCallback); } this._includeExplanations(optionsOrExplanationsCallback, explanationsCallback); return this; } timings(timings) { this._includeTimings(timings); return this; } waitForNonStaleResults(waitTimeout = null) { this._waitForNonStaleResults(waitTimeout); return this; } addParameter(name, value) { super.addParameter(name, value); return this; } addOrder(fieldName, descending, ordering = "String") { if (descending) { this.orderByDescending(fieldName, ordering); } else { this.orderBy(fieldName, ordering); } return this; } // TBD public IDocumentQuery<T> AddOrder<TValue>(Expression<Func<T, TValue>> propertySelector, bool descending, OrderingType ordering) // TBD void IQueryBase<T, IDocumentQuery<T>>.AfterStreamExecuted(Action<BlittableJsonReaderObject> action) // TBD void IQueryBase<T, IRawDocumentQuery<T>>.AfterStreamExecuted(Action<BlittableJsonReaderObject> action) openSubclause() { this._openSubclause(); return this; } closeSubclause() { this._closeSubclause(); return this; } negateNext() { this._negateNext(); return this; } search(fieldName, searchTerms, operator) { this._search(fieldName, searchTerms, operator); return this; } // TBD public IDocumentQuery<T> Search<TValue>(Expression<Func<T, TValue>> propertySelector, string searchTerms, SearchOperator @operator) intersect() { this._intersect(); return this; } containsAny(fieldName, values) { this._containsAny(fieldName, values); return this; } // TBD public IDocumentQuery<T> ContainsAny<TValue>(Expression<Func<T, TValue>> propertySelector, IEnumerable<TValue> values) containsAll(fieldName, values) { this._containsAll(fieldName, values); return this; } // TBD public IDocumentQuery<T> ContainsAll<TValue>(Expression<Func<T, TValue>> propertySelector, IEnumerable<TValue> values) statistics(stats) { this._statistics(stats); return this; } usingDefaultOperator(queryOperator) { this._usingDefaultOperator(queryOperator); return this; } noTracking() { this._noTracking(); return this; } noCaching() { this._noCaching(); return this; } include(pathOrIncludes) { if (TypeUtil_js_1.TypeUtil.isFunction(pathOrIncludes)) { const includesBuilder = new QueryIncludeBuilder_js_1.QueryIncludeBuilder(this.conventions); pathOrIncludes(includesBuilder); this._include(includesBuilder); } else if (TypeUtil_js_1.TypeUtil.isString(pathOrIncludes)) { this._include(pathOrIncludes); } else { (0, index_js_1.throwError)("InvalidArgumentException", "include() accepts either string or function."); } return this; } // TBD: IDocumentQuery<T> IDocumentQueryBase<T, IDocumentQuery<T>>.Include(Expression<Func<T, object>> path) not() { this.negateNext(); return this; } take(count) { this._take(count); return this; } skip(count) { this._skip(count); return this; } whereLucene(fieldName, whereClause, exact) { this._whereLucene(fieldName, whereClause, exact); return this; } whereEquals(...args) { this._whereEquals(...args); return this; } whereNotEquals(...args) { this._whereNotEquals(...args); return this; } whereIn(...args) { this._whereIn(...args); return this; } whereStartsWith(fieldName, value, exact) { this._whereStartsWith(fieldName, value, exact); return this; } whereEndsWith(fieldName, value, exact) { this._whereEndsWith(fieldName, value, exact); return this; } whereBetween(...args) { this._whereBetween(...args); return this; } whereGreaterThan(...args) { this._whereGreaterThan(...args); return this; } whereGreaterThanOrEqual(...args) { this._whereGreaterThanOrEqual(...args); return this; } whereLessThan(...args) { this._whereLessThan(...args); return this; } whereLessThanOrEqual(...args) { this._whereLessThanOrEqual(...args); return this; } // TBD public IDocumentQuery<T> WhereGreaterThan<TValue>(Expression<Func<T, TValue>> propertySelector, TValue value, bool exact = false) // TBD public IDocumentQuery<T> WhereGreaterThanOrEqual<TValue>(Expression<Func<T, TValue>> propertySelector, TValue value, bool exact = false) // TBD public IDocumentQuery<T> WhereLessThanOrEqual<TValue>(Expression<Func<T, TValue>> propertySelector, TValue value, bool exact = false) // TBD public IDocumentQuery<T> WhereLessThanOrEqual<TValue>( // Expression<Func<T, TValue>> propertySelector, TValue value, bool exact = false) // TBD public IDocumentQuery<T> WhereExists<TValue>(Expression<Func<T, TValue>> propertySelector) whereExists(fieldName) { this._whereExists(fieldName); return this; } // TBD IDocumentQuery<T> IFilterDocumentQueryBase<T, IDocumentQuery<T>>.WhereRegex<TValue>(Expression<Func<T, TValue>> propertySelector, string pattern) whereRegex(fieldName, pattern) { this._whereRegex(fieldName, pattern); return this; } andAlso(wrapPreviousQueryClauses) { this._andAlso(wrapPreviousQueryClauses); return this; } orElse() { this._orElse(); return this; } boost(boost) { this._boost(boost); return this; } fuzzy(fuzzy) { this._fuzzy(fuzzy); return this; } proximity(proximity) { this._proximity(proximity); return this; } randomOrdering(seed) { this._randomOrdering(seed); return this; } groupBy(...args) { this._groupBy(...args); return new GroupByDocumentQuery_js_1.GroupByDocumentQuery(this); } ofType(tResultClass) { if (tResultClass) { this._theSession.conventions.tryRegisterJsType(tResultClass); } return this.createDocumentQueryInternal(tResultClass); } orderBy(...args) { this._orderBy(...args); return this; } orderByDescending(...args) { this._orderByDescending(...args); return this; } createDocumentQueryInternal(resultClass, queryData) { let newFieldsToFetch; if (queryData && queryData.fields.length > 0) { let { fields } = queryData; if (!this._isGroupBy) { const identityProperty = this.conventions.getIdentityProperty(resultClass); if (identityProperty) { fields = queryData.fields.map(p => p === identityProperty ? Constants_js_1.CONSTANTS.Documents.Indexing.Fields.DOCUMENT_ID_FIELD_NAME : p); } } let sourceAliasReference; DocumentQuery._getSourceAliasIfExists(resultClass, queryData, fields, s => sourceAliasReference = s); newFieldsToFetch = FieldsToFetchToken_js_1.FieldsToFetchToken.create(fields, queryData.projections, queryData.isCustomFunction, sourceAliasReference); } else { newFieldsToFetch = null; if (this.fieldsToFetchToken) { queryData = new QueryData_js_1.QueryData(this.fieldsToFetchToken.fieldsToFetch, this.fieldsToFetchToken.projections, this._fromToken.alias(), this._declareTokens, this._loadTokens, this.fieldsToFetchToken.customFunction); queryData.projectionBehavior = this.projectionBehavior; } } if (newFieldsToFetch) { this._updateFieldsToFetchToken(newFieldsToFetch); } const query = new DocumentQuery(resultClass, this._theSession, this.indexName, this.collectionName, this._isGroupBy, queryData ? queryData.declareTokens : null, queryData ? queryData.loadTokens : null, queryData ? queryData.fromAlias : null, queryData ? queryData.isProjectInto : null); query._queryRaw = this._queryRaw; query._pageSize = this._pageSize; query._selectTokens = this._selectTokens; query.fieldsToFetchToken = this.fieldsToFetchToken; query._whereTokens = this._whereTokens; query._orderByTokens = this._orderByTokens; query._groupByTokens = this._groupByTokens; query._filterTokens = this._filterTokens; query._queryParameters = this._queryParameters; query._filterModeStack = [...this._filterModeStack]; query._start = this._start; query._timeout = this._timeout; query._queryStats = queryData?.queryStatistics ?? this._queryStats; query._theWaitForNonStaleResults = this._theWaitForNonStaleResults; query._negate = this._negate; //noinspection unchecked query._documentIncludes = new Set(this._documentIncludes); query._counterIncludesTokens = this._counterIncludesTokens; query._timeSeriesIncludesTokens = this._timeSeriesIncludesTokens; query._revisionsIncludesTokens = this._revisionsIncludesTokens; query._compareExchangeValueIncludesTokens = this._compareExchangeValueIncludesTokens; query._rootTypes = new Set([this._clazz]); for (const listener of query.listeners("beforeQuery")) { query.on("beforeQuery", listener); } for (const listener of query.listeners("afterQuery")) { query.on("afterQuery", listener); } for (const listener of query.listeners("afterStreamExecuted")) { query.on("afterStreamExecuted", listener); } query._explanations = this._explanations; query._explanationToken = this._explanationToken; query._queryTimings = this._queryTimings; query._queryHighlightings = this._queryHighlightings; query._highlightingTokens = this._highlightingTokens; query._disableEntitiesTracking = this._disableEntitiesTracking; query._disableCaching = this._disableCaching; query.projectionBehavior = queryData ? queryData.projectionBehavior : this.projectionBehavior; query._isIntersect = this._isIntersect; query._defaultOperator = this._defaultOperator; query._filterLimit = this._filterLimit; return query; } aggregateBy(facetOrFacetBuilder, ...facets) { if (TypeUtil_js_1.TypeUtil.isNullOrUndefined(facetOrFacetBuilder)) { (0, index_js_1.throwError)("InvalidArgumentException", "Facet or facet builder cannot be null."); } const argType = typeof facetOrFacetBuilder; if (argType === "function") { const ff = new FacetBuilder_js_1.FacetBuilder(); facetOrFacetBuilder(ff); return this.aggregateBy(ff.getFacet()); } for (const facet of [facetOrFacetBuilder, ...facets]) { this._aggregateBy(facet); } return new AggregationDocumentQuery_js_1.AggregationDocumentQuery(this); } aggregateUsing(facetSetupDocumentId) { this._aggregateUsing(facetSetupDocumentId); return new AggregationDocumentQuery_js_1.AggregationDocumentQuery(this); } highlight(parameters, hightlightingsCallback) { this._highlight(parameters, hightlightingsCallback); return this; } spatial(fieldNameOrField, clause) { const criteria = clause(SpatialCriteriaFactory_js_1.SpatialCriteriaFactory.INSTANCE); this._spatial(fieldNameOrField, criteria); return this; } /** * Filter matches to be inside the specified radius */ withinRadiusOf(fieldName, radius, latitude, longitude, radiusUnits = null, distanceErrorPct = Constants_js_1.CONSTANTS.Documents.Indexing.Spatial.DEFAULT_DISTANCE_ERROR_PCT) { this._withinRadiusOf(fieldName, radius, latitude, longitude, radiusUnits, distanceErrorPct); return this; } relatesToShape(fieldName, shapeWkt, relation, distanceErrorPctOrUnits, distanceErrorPct) { let units; if (TypeUtil_js_1.TypeUtil.isNullOrUndefined(distanceErrorPct)) { if (TypeUtil_js_1.TypeUtil.isString(distanceErrorPctOrUnits)) { units = distanceErrorPctOrUnits; distanceErrorPct = Constants_js_1.CONSTANTS.Documents.Indexing.Spatial.DEFAULT_DISTANCE_ERROR_PCT; } else { units = null; distanceErrorPct = distanceErrorPctOrUnits; } } else { units = distanceErrorPctOrUnits; } this._spatialByShapeWkt(fieldName, shapeWkt, relation, units, distanceErrorPct); return this; } orderByDistance(...args) { this._orderByDistance(...args); return this; } orderByDistanceDescending(...args) { this._orderByDistanceDescending(...args); return this; } moreLikeThis(moreLikeThisBaseOrBuilder) { if (moreLikeThisBaseOrBuilder instanceof MoreLikeThisBase_js_1.MoreLikeThisBase) { const mlt = this._moreLikeThis(); try { mlt.withOptions(moreLikeThisBaseOrBuilder.options); if (moreLikeThisBaseOrBuilder instanceof MoreLikeThisUsingDocument_js_1.MoreLikeThisUsingDocument) { mlt.withDocument(moreLikeThisBaseOrBuilder.documentJson); } } finally { mlt.dispose(); } } else { const f = new MoreLikeThisBuilder_js_1.MoreLikeThisBuilder(); moreLikeThisBaseOrBuilder(f); const moreLikeThis = this._moreLikeThis(); try { moreLikeThis.withOptions(f.getMoreLikeThis().options); const innerMoreLikeThis = f.getMoreLikeThis(); if (innerMoreLikeThis instanceof MoreLikeThisUsingDocument_js_1.MoreLikeThisUsingDocument) { moreLikeThis.withDocument(innerMoreLikeThis.documentJson); } else if (innerMoreLikeThis instanceof MoreLikeThisUsingDocumentForDocumentQuery_js_1.MoreLikeThisUsingDocumentForDocumentQuery) { innerMoreLikeThis.forDocumentQuery(this); } } finally { moreLikeThis.dispose(); } } return this; } suggestUsing(suggestBaseOrBuilder) { if (suggestBaseOrBuilder instanceof SuggestionBase_js_1.SuggestionBase) { this._suggestUsing(suggestBaseOrBuilder); return new SuggestionDocumentQuery_js_1.SuggestionDocumentQuery(this); } else { const f = new SuggestionBuilder_js_1.SuggestionBuilder(); suggestBaseOrBuilder(f); this.suggestUsing(f.suggestion); return new SuggestionDocumentQuery_js_1.SuggestionDocumentQuery(this); } } filter(builder, limit) { limit ??= Number.MAX_SAFE_INTEGER; const mode = this.setFilterMode(true); try { const f = new FilterFactory_js_1.FilterFactory(this, limit); builder(f); } finally { mode.dispose(); } return this; } shardContext(action) { this._shardContext(action); return this; } /** * Performs a vector similarity search using the specified field and embedding vector. * @param fieldName Field containing vector values or a function that returns a field using the vector factory * @param valueFactory The vector to compare against as a function, array of numbers, or string * @param options Additional vector search options */ vectorSearch(fieldName, valueFactory, options) { this._vectorSearch(fieldName, valueFactory, options); return this; } } exports.DocumentQuery = DocumentQuery; //# sourceMappingURL=DocumentQuery.js.map